Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Overloading Arithmetic Assignment Operators
Index -> Programming, C++ -> C++ Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Zampano




PostPosted: 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?



rational.cpp
 Description:
Rational class

Download
 Filename:  rational.cpp
 Filesize:  3.59 KB
 Downloaded:  300 Time(s)

Sponsor
Sponsor
Sponsor
sponsor
OneOffDriveByPoster




PostPosted: 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.
Zampano




PostPosted: 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.
wtd




PostPosted: Fri Jun 27, 2008 4:59 pm   Post subject: RE:Overloading Arithmetic Assignment Operators

Be embarassed, but be glad.
Display posts from previous:   
   Index -> Programming, C++ -> C++ Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 4 Posts ]
Jump to:   


Style:  
Search: