簡體   English   中英

鏈表中的遞增 ++ 運算符重載

[英]Increment ++ Operator overloading in linked list

我想通過將current = current->next更改為current++來增加下一個節點,但它不起作用。 所以我嘗試使用迭代器 class 來執行運算符重載。 但是有一個錯誤,我不確定這里會發生什么:

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

但事實證明有一個錯誤

你不能有一個一半使用指針一半使用迭代器的循環。 選擇一個或另一個。 例如使用迭代器

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

現在這個循環意味着你還必須為你的迭代器重載operator!=operator-> 重載operator==operator*也是有意義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM