【发布时间】:2020-12-23 15:40:04
【问题描述】:
我想通过将current = current->next 更改为current++ 来增加下一个节点,但它不起作用。所以我尝试使用迭代器类来执行运算符重载。但是有一个错误,我不确定这里会发生什么:
struct node{
int value;
node *next;
}
class Iterator{
public:
Iterator();
Iterator(node *);
Iterator operator++(int);
private:
node *point;
};
Iterator::Iterator(){
point = NULL;
}
Iterator::Iterator(node *current){
point = current;
}
Iterator Iterator::operator++(int u){
point = point->next;
return *this;
}
打印出来是这样的:
class linkedList{
public:
void print() const;
protected:
node *first;
}
void linkedList::print()const{
node *current = first;
Iterator p = Iterator(current);
while(current != NULL){
cout << current->value << " ";
p++;
}
}
但事实证明有一个错误
【问题讨论】:
-
为什么你期望调用
p++会影响current的值?p有自己的node*、point,它开始等于current,但随后发生变化。 -
您需要将运算符
->和!=添加到您的迭代器类中,以便通过for (Iterator it(first), end; it != end; ++it) std::cout << it->value << '\n';进行迭代 -
“原来有一个错误”是什么意思?请在问题中包含您的代码的minimal reproducible example 并解释问题所在
标签: c++ linked-list operator-overloading