I have defined an overload for operator -= for my Rational-class:
rational.hh:
class Rational {
public:
Rational(int numerator, int denominator) : numerator(numerator), denominator(denominator)
{ }
int getNumerator() const;
int getDenominator() const;
Rational& operator-=(const Rational& bar);
private:
int numerator, denominator;
rational.cc:
Rational& Rational::operator-=(const Rational& subtracted) {
Rational result((*this).getNumerator()*subtracted.getDenominator() - (*this).getDenominator()*subtracted.getNumerator(), (*this).getDenominator()*subtracted.getDenominator());
return *this;
}
The code compiles without warnings but this piece of code does not change the value of r:
Rational r(1, 1);
r -= Rational(1, 2);
Any ideas why?
Your
-=operator should be changing the values ofnumeratoranddenominator, but it does not. Add code to set these values intothis, instead of creatingresult: