【发布时间】:2021-06-10 04:43:23
【问题描述】:
我正在练习为自定义类实现随机访问迭代器:
template<typename T>
class Array{
friend class Iterator;
private:
std::unique_ptr<T[]> data;
int front_index;
//other variables
public:
class Iterator{
friend class Array<T>;
private:
int position;
public:
Iterator(int pos) {position = pos; }
//some other iterator functions
template<typename T>
T operator*(){
return data[position];
}
};
Iterator begin() const { return Iterator(front_index); }
//other Array functions(insert, delete)
};
但是当我调用这段代码时:
Array<int> a;
//insert some elements
Array<int>::Iterator iter1 = a.begin();
cout << "iterator is " << *iter1 << endl;
它给出了以下错误:
C++ no operator matches these operands, operand types are: * Array<int>::Iterator
似乎错误来自return data[position]; 行。如果我只写
return position 代码运行,但这不是我想要的(我希望当我取消引用时 ierator 返回特定位置的元素。感谢任何输入!
【问题讨论】:
-
看起来像是一条错误的错误消息。
data在Iterator中无法访问,因为您从未告诉它data是什么。 C++ 中的内部classes 与外部class没有自动关系。 -
@eerorika
data是Array的成员。而Iterator成为朋友并不会神奇地使其能够访问Arrays 成员。 -
@super 哦,是的,这是真的。 name 可访问,但无法通过非限定查找找到。
标签: c++ iterator overloading