Overloading Arithmetic Assignment Operators
Author |
Message |
Zampano
![](http://compsci.ca/v3/uploads/user_avatars/123384421747e86c6cddac1.gif)
|
Posted: 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?
Description: |
|
![](http://compsci.ca/v3/pafiledb/images/icons/clip.gif) Download |
Filename: |
rational.cpp |
Filesize: |
3.59 KB |
Downloaded: |
300 Time(s) |
|
|
|
|
|
![](images/spacer.gif) |
Sponsor Sponsor
![Sponsor Sponsor](templates/subSilver/images/ranks/stars_rank5.gif)
|
|
![](images/spacer.gif) |
OneOffDriveByPoster
|
Posted: 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.
|
|
|
|
|
![](images/spacer.gif) |
Zampano
![](http://compsci.ca/v3/uploads/user_avatars/123384421747e86c6cddac1.gif)
|
Posted: 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.
|
|
|
|
|
![](images/spacer.gif) |
wtd
|
Posted: Fri Jun 27, 2008 4:59 pm Post subject: RE:Overloading Arithmetic Assignment Operators |
|
|
Be embarassed, but be glad.
|
|
|
|
|
![](images/spacer.gif) |
|
|