增量运算符/迭代器实现

时间:2010-12-01 22:11:34

标签: c++ iterator linked-list post-increment

我想在这里弄清楚几件事:

  1. 如何为具有指向下一个节点的指针的节点类编写增量运算符?
  2. 如何为下面的类实现迭代器?

    #include <iostream>
    #include <vector>
    using namespace std;
    
    template <typename T>
    class Node {
    public:
        Node(int i=0):val(i) {}
        Node*& operator++(int i=0) {return next;};
    
        T val;
        Node *next;
    };
    
    //================================================
    int main() {
    
        Node<int> *head, *tmp1, *tmp2;
    
        tmp1 = new Node<int>(0); 
        head = tmp1;
    
        for (int i=1; i<10; ++i) {
    
            tmp2 = new Node<int>(i);
            tmp1->next = tmp2;
            tmp1 = tmp2;
        }
    
        while (head != NULL) {
    
            cout << head->val << " '";
            head = head->operator++(0);    //How do I make it work with ++head;?
        }
    }
    
  3. 这不是演示运算符重载或迭代器的好例子。

1 个答案:

答案 0 :(得分:11)