class test {
public:
test &operator=(const test & other){} // 1
const test & operator+(const test& other) const {} // 2
const test & operator+(int m) {} //3
private:
int n;
};
int main()
{
test t1 , t2, t3;
// this works fine t1 = t2.operator+(t3) , calls 2 and 1
t1 = t2 + t3;
// this works fine t1 = t2.operator+ (100). calls 3 and 1
t1 = t2 + 100;
//this works fine t1 = (t2.operator+ (100)).operator+ (t3)
t1 = t2 + 100 +t3;
//why is the error in this one ????
// it should be t1 = (t2.operator+ (t3)).operator+ (100)
t1 = t2 + t3 + 100;
return 0;
}
views:
152answers:
3
+8
A:
Because object returned by t2+t3 is const, and you cannot call its non-const function (3).
It works fine in case of "t1 = t2 + 100 +t3;", because object returned by t2+100 is const too, but you are calling its const function (2), which is ok.
Igor Oks
2009-01-24 08:54:02
Alien01
2009-01-24 09:04:47
A:
- Change X to test.
- Add a semicolon to the end of the penultimate statement.
- Remove the const from the addition operator return values as you're modifying them.
The following compiles:
class test {
public:
test& operator=(const test & other){} // 1
test& operator+(const X& other) const {} // 2
test& operator+(int m) {} //3
private:
int n;
};
int main()
{
test t1, t2, t3;
t1 = t2 + t3;
t1 = t2 + 100;
t1 = t2 + 100 + t3; // <-- added a ';'
t1 = t2 + t3 + 100;
return 0;
}
Steve Lacey
2009-01-24 08:57:28
+1
A:
You missed a const:
const test & operator+(int m) /* ADD CONST HERE */ const {} //3
Martin York
2009-01-24 15:30:57