Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overload operator of a nested class?

Tags:

c++

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?

like image 534
Instinct Avatar asked Nov 05 '12 22:11

Instinct


People also ask

What is the correct way to overload operator?

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.

How do you overload operators in Java?

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.

Can we overload a class access operator?

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.

Can we overload == operator in C++?

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.


1 Answers

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
}
like image 178
Syntactic Fructose Avatar answered Sep 24 '22 23:09

Syntactic Fructose