Computer Science Canada

Overloading Arithmetic Assignment Operators

Author:  Zampano [ Fri Jun 27, 2008 12:09 pm ]
Post subject:  Overloading Arithmetic Assignment Operators

The book I'm using told me to overload these operators like this (example using a fractions class):
code:
rational& operator += (const rational& x) {
        den *= x.den;
        num = num * x.den + den * x.num;
        reduce ();
        return *this;
}

with the function being declared as public. However, g++ gave an error asking that arithmetic assignment operators always have two parameters. So, I made the function declaration:
code:
friend rational& operator += (rational&, const rational&);

and the implementation to:
code:
rational& operator += (rational& x, const rational& y) {
        x.den *= y.den;
        x.num = x.num * y.den + y.num * x.den;
        x.reduce ();
        return *this;
}

because at that point I had lost myself and wasn't sure if a number of things were valid, such as *this with no owner object. No the compiler gives errors because it can't read the num and den, the two private variables, even though the function is a friend.
I attach the rest of the code, declaration, implementation, and driver (testing the assignment operator) in one file.
Help, please?

Author:  OneOffDriveByPoster [ Fri Jun 27, 2008 2:35 pm ]
Post subject:  Re: Overloading Arithmetic Assignment Operators

You should return x instead of *this. You still had the x as a const reference in the attached file--fix it.

Author:  Zampano [ Fri Jun 27, 2008 4:13 pm ]
Post subject:  Re: Overloading Arithmetic Assignment Operators

*gulps* Uh, thanks.
I'm a bit embarrassed that it was such a little problem.

Author:  wtd [ Fri Jun 27, 2008 4:59 pm ]
Post subject:  RE:Overloading Arithmetic Assignment Operators

Be embarassed, but be glad.


: