简体   繁体   中英

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. So I try to use an iterator class to perform operator overloading. 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. It would also make sense to overload operator== and operator* .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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