Re: overloading for multiple arithmetic operations
On 2010-07-13 12:43:44 -0400, Dominic Chandar said:
Hi,
I would like to add multiple objects of a class with integers/
floats. Need some basic help in fixing an error
Eg:
#include<iostream>
using namespace std;
class Test
{
public:
Test(float _code){ code = _code;}
Test(){}
float code;
friend Test operator+(Test & ob, float val);
friend Test operator+(float val, Test & ob);
Test operator+(Test & ob);
};
Test Test::operator+(Test & ob)
{
Test temp;
temp.code = this->code + ob.code;
return temp;
}
Test operator+(Test & ob, float val)
{
Test temp;
temp.code = ob.code + val;
return temp;
}
Test operator+(float val, Test & ob)
{
Test temp;
temp.code = ob.code + val;
return temp;
}
int main()
{
Test ob1(1.0), ob2(2.0), ob3(3.0), ob4(0.0);
float c1=100.5 ;
ob4 = ob1+ob2+ob3 ; // This works
ob4 = ob1+c1; // This works
ob4 = ob1 + ob2 + c1 ;// Does not work... why ?
ob4 = ob1 + c1 + ob2 ;// This works...
return 0;
}
My question is : why does the third operation ob4 = ob1 + ob2 + c1
fail ?
Presumably "fail" here means "doesn't compile and produces error
messages that haven't been included in this message". Error messages
are your friend! Read them!
Off hand, it looks like ob1 + ob2 is returning a Test object, and since
operator+ takes a non-const Test object, it can't be called with a
temporary. Both free functions should take their Test object by const
reference or by value, and the member operator+ should be marked const.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]