简体   繁体   English

链表中的递增 ++ 运算符重载

[英]Increment ++ Operator overloading in linked list

I want to increment the next node by changing the current = current->next to current++ but it does not work.我想通过将current = current->next更改为current++来增加下一个节点,但它不起作用。 So I try to use an iterator class to perform operator overloading.所以我尝试使用迭代器 class 来执行运算符重载。 But there is a bug, I am not sure what happens here:但是有一个错误,我不确定这里会发生什么:

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;
}

and the print is like:和打印是这样的:

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++;
   }
}

but it turns out there is a bug但事实证明有一个错误

You can't have a loop that half uses a pointer and half uses an iterator.你不能有一个一半使用指针一半使用迭代器的循环。 Pick one or the other.选择一个或另一个。 For instance with an iterator例如使用迭代器

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

Now this loop means you also have to overload operator!= and operator-> for your iterator.现在这个循环意味着你还必须为你的迭代器重载operator!=operator-> It would also make sense to overload operator== and operator* .重载operator==operator*也是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM