
-----------------------------------
Zampano
Fri Jun 27, 2008 12:09 pm

Overloading Arithmetic Assignment Operators
-----------------------------------
The book I'm using told me to overload these operators like this (example using a fractions class):
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:
friend rational& operator += (rational&, const rational&);
and the implementation to:
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?

-----------------------------------
OneOffDriveByPoster
Fri Jun 27, 2008 2:35 pm

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.

-----------------------------------
Zampano
Fri Jun 27, 2008 4:13 pm

Re: Overloading Arithmetic Assignment Operators
-----------------------------------
*gulps* Uh, thanks.
I'm a bit embarrassed that it was such a little problem.

-----------------------------------
wtd
Fri Jun 27, 2008 4:59 pm

RE:Overloading Arithmetic Assignment Operators
-----------------------------------
Be embarassed, but be glad.
