Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading