簡體   English   中英

操作員超載

[英]Operator overload

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

由於t2 + t3返回的對象是const,因此您不能調用其非const函數(3)。

在“ t1 = t2 + 100 + t3;”的情況下,它可以正常工作,因為t2 + 100返回的對象也是const,但是您可以調用它的const函數(2),這沒關系。

  1. 更改X進行測試。
  2. 在倒數第二個語句的末尾添加分號。
  3. 在修改它們時,從加法運算符返回值中刪除const。

編譯如下:

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

您錯過了一個常量:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM