我制作了这个测试程序来复制我实际代码中的错误。当stuff()
被注释掉时,在主函数中调用时,迭代器可以正常工作。 stuff()
使编译器抛出错误。我想原因是主机类在编译时不是对象...所以不是l值?不幸的是,我不太知道谷歌要找到关于如何做这样的工作的解释。
#include <iostream>
class Foo
{
class Iterator;
public:
Foo() { init(); }
Iterator begin()
{
return Iterator(data);
}
Iterator end()
{
return Iterator(data+10);
}
void stuff()
{
for (auto i = begin(); i != end(); ++i)
{
1 + 1;
}
}
private:
class Iterator
{
public:
Iterator(int* i)
{
current = i;
}
bool operator!=(Iterator& rhs)
{
return rhs.current != current;
}
Iterator& operator++()
{
current = ++current;
return *this;
}
int* operator*()
{
return current;
}
private:
int* current;
};
void init()
{
for (int i = 0; i < 10; ++i)
{
data[i] = i;
}
}
int data[10];
};
int main()
{
Foo foo;
for (auto i : foo)
{
std::cout << *i << std::endl;
}
}
错误:
itertest.cpp:31:31: error: invalid operands to binary expression ('Foo::Iterator' and 'Foo::Iterator')
for (auto i = begin(); i != end(); ++i)
~ ^ ~~~~~
itertest.cpp:49:7: note: candidate function not viable: expects an l-value for 1st argument
bool operator!=(Iterator& rhs)