Home > OS >  The division operation of overloaded function operators leads to the change of divisor
The division operation of overloaded function operators leads to the change of divisor

Time:04-10

when I build a class named "Money", I overloaded the "/" sign in the class. But the divisor changed during the division operation. As shown below:

(1.This is the declaration of overloaded function operators in the header file)

Money& operator/(double);
void division(double);

(2.This is the specific definition of overloaded operator)

void Money::division(double i)
{
money_number = money_number / i;
}


Money& Money::operator/(double i)
{
division(i);
return *this;
}

(3.This is my call to it in the main function)

Money money_temp=100;
Money mmm = 0;
cout <<"mmm" << money_temp << endl;
mmm = money_temp / 2;
cout << "mmm" << money_temp << endl;

But I found that in the end “money_temp” changed after division. it became 50 from 100. I try to delete the "&" in the "Money& operator/(double);" , but I failed.

How to resolve this problem? Thanks for your kind help.

CodePudding user response:

Problem:

In Money::division you're modifying the object through the statement money_number = money_number / i;, which assigns a new value to money_number.

Solution:

Create a copy of the object in the division and return that instead.

Code:

Money Money::operator/(double i)
{
    Money temp = money_number / i;
    return temp;
}

Note that I deleted the & because it would lead to a dangling reference otherwise.

  •  Tags:  
  • c
  • Related