【发布时间】:2020-05-26 21:23:53
【问题描述】:
我收到以下错误:
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;
}
};
};
事实证明,将begin 函数移到嵌套的Iterator 类可以编译。
但这很奇怪 - 嵌套类不遵循与任何其他成员相同的访问规则,这意味着不需要前向引用?
我搜索了网站上关于这个确切问题的其他问题,似乎没有找到答案。
【问题讨论】:
-
Iterator 是什么意思?!内部类应该在使用它的名字之前声明。
-
@VladfromMoscow 我明白了。我当然认为是这样,但是,正如我在此处指出的那样,我在 SO 上读到可能并非如此。另外 - 我在成员函数
q中调用成员函数f没有问题,其中f在q之后定义。你能解释一下为什么后一个例子与这个问题中描述的情况不同吗?谢谢
标签: c++ class scope nested declaration