【问题标题】:Increment ++ Operator overloading in linked list链表中的递增 ++ 运算符重载
【发布时间】: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,但随后发生变化。
  • 您需要将运算符-&gt;!= 添加到您的迭代器类中,以便通过for (Iterator it(first), end; it != end; ++it) std::cout &lt;&lt; it-&gt;value &lt;&lt; '\n'; 进行迭代
  • “原来有一个错误”是什么意思?请在问题中包含您的代码的minimal reproducible example 并解释问题所在

标签: c++ linked-list operator-overloading


【解决方案1】:

你不能有一个一半使用指针一半使用迭代器的循环。选择一个或另一个。例如使用迭代器

Iterator p = Iterator(current);
while (current != Iterator()){
    cout << p->value << " ";
    p++;
}

现在这个循环意味着你还必须为你的迭代器重载operator!=operator-&gt;。重载operator==operator* 也是有意义的。

【讨论】:

  • 请注意,此代码在每次循环迭代时都会创建一个新的临时 Iterator 对象,应该避免这种情况。
  • @RemyLebeau 我希望它会被优化掉。即使不是,这个迭代器的构建成本也差不多。
  • 也许也许不是,这取决于编译器。但是,如果您不必重复,确实没有必要故意重复。一个简单的调整就足够了:Iterator p(current), end; while (p != end) { ... p++; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-06
  • 1970-01-01
  • 2012-03-23
  • 1970-01-01
  • 2014-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多