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 ++?
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 ++?
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.
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? - megaA good example is given here: operator overloading .
Source: https://ru.stackoverflow.com/questions/163541/
All Articles