tags:

views:

152

answers:

3
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;
}
+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
Alien01
A: 
  1. Change X to test.
  2. Add a semicolon to the end of the penultimate statement.
  3. 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
+1  A: 

You missed a const:

const test & operator+(int m) /* ADD CONST HERE */ const {} //3
Martin York