I have made a simple program to print out numbers by using arithmetic operations. Every thing works fine, except last operator. It prints result as : 1
which is wrong and the expected result should be 1.7
.
What is wrong with my program I have made. Why does it print like this?
#include <iostream>
#include <exception>
class Money
{
public:
Money(float amount = 0) : m_amount(amount){}
// logic operations
bool operator==(const Money& other) const
{
return m_amount == other.m_amount;
}
// arithmetic operations
Money operator*=(const Money& other)
{
m_amount *= other.m_amount;
return *this;
}
Money operator/=(const Money& other)
{
if (other.m_amount == 0)
throw std::invalid_argument("Division by zero");
m_amount /= other.m_amount;
return *this;
}
friend std::ostream& operator<<(std::ostream& os, const Money& money)
{
return os << '$' << money.m_amount;
}
private:
float m_amount;
};
int main()
{
Money my_money(1.7f);
std::cout << (my_money *= my_money) << '\n';
std::cout << (my_money /= my_money) << '\n'; // <-- wrong it should be 1.7
}