I am writing a a linked list and I have an Iterator class within my List class. I want to overload the = operator but I don't know the correct syntax to start it.
This is what I have in my code
class List{
//member stuff
class Iterator{
private: Node* current;
public: Iterator& operator=(const Iterator& right);
}
}
I am trying this but I am unsure whether this is correct or not.
List::Iterator::operator=(const Iterator& right){
//stuff
}
Can anyone clarify?
In case of operator overloading all parameters must be of the different type than the class or struct that declares the operator. Method overloading is used to create several methods with the same name that performs similar tasks on similar data types.
Java doesn't supports operator overloading because it's just a choice made by its creators who wanted to keep the language more simple. Every operator has a good meaning with its arithmetic operation it performs.
The class member access operator (->) can be overloaded but it is bit trickier. It is defined to give a class type a "pointer-like" behavior. The operator -> must be a member function. If used, its return type must be a pointer or an object of a class to which you can apply.
Overloading Binary Operators Suppose that we wish to overload the binary operator == to compare two Point objects. We could do it as a member function or non-member function. To overload as a member function, the declaration is as follows: class Point { public: bool operator==(const Point & rhs) const; // p1.
To clarify, your thoughts are correct, but you forgot to have a return type in your function declaration:
List::Iterator::operator=(const Iterator& right){
//stuff
}
needs to be
List::Iterator& List::Iterator::operator=(const Iterator& right){
//stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With