开发者

+= Overloading in C++ problem

I am trying to overload the += operator for my rational number class, but I don't believe that it's working because I always end up with the same result:

RationalNumber RationalNumber::operator+=(const RationalNumber &rhs){

   int den = denominator * rhs.denominator;

   int a = numerator * rhs.denominator;
   int b = rhs.numerator * denomin开发者_Python百科ator;
   int num = a+b;

   RationalNumber ratNum(num, den);
   return ratNum;
}

Inside main

//create two rational numbers
RationalNumber a(1, 3);
a.print();

RationalNumber b(6, 7);
b.print();

//test += operator
a+=(b);
a.print();

After calling a+=(b), a is still 1/3, it should be 25/21. Any ideas what I am doing wrong?


operator+= is supposed to modify the object itself and return a reference. You are instead creating a new object and returning that. Something like this might work (untested code):

RationalNumber &RationalNumber::operator+=(const RationalNumber &rhs){

   int den = denominator * rhs.denominator;

   int a = numerator * rhs.denominator;
   int b = rhs.numerator * denominator;
   int num = a+b;

   numerator = num;
   denominator = den;
   return *this;
}

Likewise operator+ should return a new object and can almost always be implemented in terms of operator+=:

RationalNumber RationalNumber::operator+(const RationalNumber &rhs){
    RationalNumber tmp(*this);
    tmp += rhs;
    return tmp;
}

Finally, (now i'm getting off topic) it is usually considered best practice to use free functions instead of members where you can for things like binary operators.


You are not changing the object the operator is applied to.

x += 3;

should change x.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜