I've been scratching my head on this one, and after sifting through all the other postings I think I've come up at a loss.
I decided I wanted to practice some template coding and operator overloading in C++, and so I figured a quick and dirty LinkList implementation would go fairly far. I quickly hacked up a node and list class set, as follows:
template <class T>
class Node{
public:
Node* getNext(){ return Next; }
private:
Node* Next;
T data;
};
template <class T>
class List{
public:
List& operator++();
private:
Node<T>* nptr;
};
template <class T>
List<T>& List<T>::operator++(){
if( nptr->getNext() ){
nptr = nptr->getNext();
}
return *this;
}
main call:
int main(){
List<int>* listObj = new listObj<int>();
...push on some nodes with random values...
++listObj;
KABOOM
}
I'm keeping the code brief for readability. Assume that I always initialize Next to NULL when I make a node, that there's a push function to add more nodes to the end which also sets the last node's 'Next' variable to that new node, and that nptr also starts off initialized as NULL. I've tested all the "assumed" functionality (construction, initialization, pushing nodes) and I can even pack the operator++ function as just a increment function...
void Increment(){
if( nptr->getNext() ){
nptr = nptr->getNext();
}
}
call:
listObj->Increment();
...and that works just fine. In otherwords: the compiler isn't assigning my version of ++foo to any uses in the code! I can even prove this with the debugger, watching it increment the address of the List object rather then updating nptr like I want.
Now, I saw a suggestion of friending the function here that I gave a try:
friend List& operator++(){
if( nptr->getNext() ){
nptr = nptr->getNext();
}
return *this;
}
However when I do, I get a compilation error:
List& operator++() must have an argument of class or enumerated type
Hard-headed programmer that I am, I figured it wanted me to scope out the incoming RHS, which naturally also didn't work. I'm forgoing writing out that broken path of reasoning because I'm fairly confident it wasn't the right direction.
So given that the compiler seems happy with my code (or at least isn't upset about it because its not actually assigning it anywhere), why is it still grabbing the non-templated version of the operator and treating it like an int? How would I go about correcting the code to get the compiler to use the provided function instead?
Thanks in advance!