How to overload the indirectness operator? (C ++)

I am trying to create an iterator class as a member class of the list class and trying to overload the indirectness operator (*) to access the list that it points to:

template<class T> T list<T>::iterator::operator*(iterator& iter) { return ((iter.lstptr)->current)->data; } 

where lstptr is a pointer to a list, current is a pointer to a node class, and node class contains a data item of type T

An iterator is declared as follows:

 template<class T> class list { public: class iterator; }; template<class T> class list<T>::iterator { //stuff }; 

I can compile the function definition of the overloaded * fine operator, but when I try to do something like:

 list<int> lst1; lst1.add(6); list<int>::iterator IT; IT = lst1; //everything above this point compiles fine int a = *IT; //error here (line fourteen) 

The error I get says <1> that I am using illegal indirectness, and <2> that it cannot convert from the :: iterator to int list. Both errors are found on the fourteenth line.

Does anyone know what I'm doing wrong, and how can I properly overload the indirectness operator?

NB: If you need to see more code, tell me which part, because I do not want to put all the code here, because it contains 205 lines and 204 of these lines are not (I think) any errors.

+7
c ++ operator-overloading indirection
source share
2 answers

You overloaded the multiplication operator. Take a parameter to make it an indirectness operator.

 template<class T> T list<T>::iterator::operator*() { return ((this->lstptr)->current)->data; } 

You also need to return the link if you want a code, for example *IT = 3; compiled.

 template<class T> T& list<T>::iterator::operator*() { return ((this->lstptr)->current)->data; } 
+12
source share

Here you have two problems; firstly, you accidentally overloaded the multiplication operator, and not the dereference operator; secondly, you did not return the reference type.

The first problem arises due to the number of parameters. Each non-static member function of the class has an additional "hidden" parameter: this . this is, of course, a pointer to the object on which the function is being called. As a result, you actually declared a statement version with two parameters. By removing the second parameter of the iterator and working on this , you will overload the unary * , not the binary.

The second problem is the minor type of the return type; you are returning a copy to the original object, not to the original object itself. Declare the return type as T& to return the link.

+5
source share

All Articles