操作员超载

时间:2009-01-24 08:41:55

标签: c++

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;
}

3 个答案:

答案 0 :(得分:8)

因为t2 + t3返回的对象是const,你不能调用它的非const函数(3)。

在“t1 = t2 + 100 + t3;”的情况下工作正常,因为t2 + 100返回的对象也是const,但是你正在调用它的const函数(2),这没关系。

答案 1 :(得分:1)

  1. 将X更改为测试。
  2. 在倒数第二个语句的末尾添加分号。
  3. 在修改它们时,从添加运算符返回值中删除const。
  4. 以下编译:

    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;
    }
    

答案 2 :(得分:1)

你错过了一个const:

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