Topper Topper - 1 year ago 117
C++ Question

Operator= Overload with different parameter in C++?

When I create an object of Example (class), I want to assign it a int value with the equal operator, just to see how operator overloading works.

But I canĀ“t compile it with the following code:


Example& Example::operator=(int number)
this->number = number;
return *this;


Example x1 = 10;

Answer Source

Despite what it looks like that is not an assignment, its an initialization. It calls the constructor, not the assignment operator.

Try this:

Example x1; // initialize
x1 = 10; // assign

In your example it is looking for a constructor that takes an int as its parameter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download