C++ 嵌套类";不为类型命名";
我得到以下错误:C++ 嵌套类";不为类型命名";,c++,class,scope,nested,declaration,C++,Class,Scope,Nested,Declaration,我得到以下错误: main.cpp:18:5: error: 'Iterator' does not name a type 18 | Iterator begin() { | ^~~~~~~~ 使用此代码: #include <iostream> #include <iostream> #include <memory> #include <fstream> #include <filesystem>
main.cpp:18:5: error: 'Iterator' does not name a type
18 | Iterator begin() {
| ^~~~~~~~
使用此代码:
#include <iostream>
#include <iostream>
#include <memory>
#include <fstream>
#include <filesystem>
using namespace std;
class Numbers {
private:
int current;
int end;
public:
Numbers(int end) : current(0), end(end) {}
Iterator begin() {
return Iterator(this);
}
bool operator==(const Numbers& other) const {
return current == other.current && end == other.end;
}
bool operator!=(const Numbers& other) const {
return !(other == *this);
}
class Iterator {
private:
Numbers* range;
public:
using value_type = int;
using difference_type = ptrdiff_t;
using pointer = int*;
using reference = int&;
using iterator_category = input_iterator_tag;
Iterator(Numbers* range) : range(range) {}
int operator*() const {
return range->current;
}
int* operator->() const {
return &range->current;
}
bool operator==(const Iterator& other) const {
return other.range == range;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
Iterator& operator++() {
range->current++;
return *this;
}
};
};
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
班级人数{
私人:
电流;
内端;
公众:
数字(int-end):当前(0),结束(end){}
迭代器begin(){
返回迭代器(this);
}
布尔运算符==(常量编号和其他)常量{
返回当前==other.current&&end==other.end;
}
布尔运算符!=(常数编号和其他)常数{
返回!(其他==*此);
}
类迭代器{
私人:
数字*范围;
公众:
使用value_type=int;
使用差分类型=ptrdiff t;
使用指针=int*;
使用reference=int&;
使用迭代器\类别=输入\迭代器\标记;
迭代器(数字*范围):范围(范围){}
整型运算符*()常量{
返回范围->当前;
}
int*运算符->()常量{
返回和范围->当前;
}
布尔运算符==(常量迭代器和其他)常量{
返回other.range==范围;
}
布尔运算符!=(常量迭代器和其他)常量{
返回!(*此==其他);
}
迭代器和运算符++(){
范围->当前++;
归还*这个;
}
};
};
事实证明,将begin
函数移动到嵌套的迭代器
类下可以进行编译
但奇怪的是,嵌套类不遵循与任何其他成员相同的访问规则,这意味着不需要向前引用吗
我在网站上搜索了关于这个问题的其他问题,似乎没有找到答案。从对该问题的评论中 另外-在成员函数中调用成员函数f没有问题 q,其中f在q之后定义。你能解释下一个例子的原因吗 与此问题中描述的情况不同吗
根据C++ 20标准(11.4类成员)
6类的完整类上下文是 >(6.1)-功能体(9.5.1), (6.2)-默认参数(9.3.3.6) (6.3)-无例外规范(14.5),或 (6.4)-默认成员初始值设定项 在类的成员规范内 因此,在完整的类上下文中,函数f
的名称在函数q
的主体中可见
但是,内部类是在完整类上下文之外声明的。所以根据C++ 20标准(65.1不合格名称查找)
7在外部的类X23定义中使用的名称
X的完整类上下文(11.4)应在下列其中一种声明中声明:
以下方法:
>(7.1)-在X类中使用之前,或是X基类的成员
(11.8),或
因此,内部类迭代器的名称必须在用作成员函数的返回类型之前声明
例如,可以使用占位符auto
作为返回类型,而不是名称迭代器
auto begin() {
return Iterator(this);
}
迭代器是什么意思?!内部类应该在使用其名称之前声明。@VladfromMoscow我明白了。我当然认为是这样的,但是,正如我在这里指出的,我继续读下去,也许不是这样的。另外-在成员函数q
中调用成员函数f
没有问题,其中f
在q
之后定义。你能解释一下为什么后一个例子与这个问题中描述的情况不同吗?谢谢你;DR:成员函数的定义隐式地“放在”类之后,因此它们可以看到类中的所有内容,即使某些内容是在编写函数体的位置之后声明的。该语言中没有“类成员不需要转发声明”规则。成员的声明按照您编写它们的顺序保留在类中,因此begin
的签名无法看到Iterator
。