Computer Science Canada

Arithmetic operator overloading.

Author:  ericfourfour [ Sun Nov 26, 2006 1:24 am ]
Post subject:  Arithmetic operator overloading.

Is there a way to make it so whenever a certain class is used in an arithmetic operation it will be represented by a double, which is a private member variable (other than overloading every arithmetic operator)?

Here is what I have and it feels like I'm writing a lot and there must be a better way. These are all inside a class called meter.
c++:
friend const double operator+ (const double&, const meter&);
friend const double operator- (const double&, const meter&);
friend const double operator* (const double&, const meter&);
friend const double operator/ (const double&, const meter&);
friend const double operator+ (const meter&, const double&);
friend const double operator- (const meter&, const double&);
friend const double operator* (const meter&, const double&);
friend const double operator/ (const meter&, const double&);
friend const double operator+ (const meter&, const meter&);
friend const double operator- (const meter&, const meter&);
friend const double operator* (const meter&, const meter&);
friend const double operator/ (const meter&, const meter&);

In case you are wondering the bodies of the functions use one of the members of the meter class and use it in the operation with the double.

Author:  Andy [ Sun Nov 26, 2006 5:41 am ]
Post subject: 

just make a macro for it and insert it into all of your classes

Author:  md [ Sun Nov 26, 2006 10:09 am ]
Post subject: 

Having seen next to no code I can't be sure this will work how you want, but you could overload () to return a double representing meter; then you wouln't need to overload all the operators. Just use meter1() + 100 / meter2().

Author:  ericfourfour [ Sun Nov 26, 2006 2:24 pm ]
Post subject: 

That's perfect md! I never would have thought of it.


: