template <typename ITEM> class List { private: struct node { ITEM item; struct node* next; }; node* head; ... } 

It is necessary that the functions inside the classes work:

 node* iter = head; ++iter; 

How to overload operator ++?

  • friend node & operator ++ (node ​​& iter) {iter = (* iter.p); return iter;}; ++ (* iter); works. But how to move the definition beyond the class declaration? - iofjuupasli

2 answers 2

How to overload operator ++?

How to move the definition outside the class declaration?

This is done by introducing an iterator class, like this:

 template <typename ITEM> class List{ ... class Iterator{ node*ptr; ... Iterator( node*ptr = NULL ) : ptr( ptr ){} ITEM*operator->( void ){ return &ptr->item; } iterator&operator++( void ){ ptr = ptr->next; return *this; } iterator operator++( int ){ node*result; // result = ptr; ptr = ptr->next; return result; } ... }; iterator begin( void ){ return head; } ... }; 

Here Iterator is a wrapper class over the node* pointer, which has overloaded operators -> and both ++ . In the program, instead of node* you just need to use Iterator , then it will work as expected, with pluses.

  • @mega, since I write in C, I have always been interested in - such (and similar to it) implementations of iterators - is this a purely demo or do real implementations also write that way? I’ll explain that I’m worried about deleting list items when using multiple iterators (and not only). - avp
  • If we consider STL , then this example is very close to it, only there the iterator class itself is moved out of the list. But this is, of course, a demonstration with a minimum of functionality. If you use objects of this class as a pointer, then the problem of deleting list items in the presence of iterator instances will be similar to the problem of deleting it if there are normal links to it. Those. I do not see any particular reason for concern. Or am I misunderstanding you? - mega
  • one
    @mega, you understood me correctly. The essential difference between ordinary links and iterators is purely psychological. Iterators look safe, but there are no explicit pointers. Therefore, iterators to a greater extent provoke hidden logical errors (this does not apply to demo). By the way, he ran into it (fortunately quickly discovered) in the Java lists. - avp
  • I agree! But this "psychological deception" is the case when using any unexplored class. Or a class whose reaction to some abstract actions as with its prototype is not well understood. For example: if the iterator does not rewrite the & operator, then 2 actions of the same nature with the prototype and its wrapper can lead to a logical error, if for some reason, the pointer offset in the iterator is nonzero: void p = (void *) & pNode; void q = (void *) & it; Nobody would like to look for such a thing :) - mega
  • 2
    @mega, a great example that demonstrates the complexity of C ++. - avp

A good example is given here: operator overloading .