[英]binary operator + , = overloading with const
我正在學習C ++概念,希望對解釋有所幫助。 為什么語句4不編譯而語句1為什么編譯。
class X {
public:
X& operator= (const X& rhs);
const X& operator+ (const X& rhs) const;
const X& operator+ (int m);
private:
int n;
};
int main() {
X a, b, c;
a = a + 5 + c; //statement 1 - No compiler errors
a = b + 5; //statement 2
a = a = b + c; //statement 3
a = b + c + 5; //statement 4 /*compiler Error thrown -
passing 'const X' as 'this' argument of 'const X& X::operator+(int)' discards qualifiers
[-fpermissive]*/
(c = a + a) = b + c; //statement 5
}
根據我的理解(基於:+和=都是右關聯的),以上5條陳述被解讀為-
//statement 1
a.operator=(a.operator+(5.operator+(c)));
->我相信這應該拋出錯誤,因為沒有定義的構造函數支持
//statement 2
a.operator=(b.operator+(5));
//statement 3
a.operator=(a.operator=(b.operator+(c)));
//statement 4
a.operator=(b.operator+(c.operator+(5)));
//statement 5
(c.operator=(a.operator+(a)))=(b.operator+(c)); then
lhs_result.operator=(rhs_result);
我也正確地解讀了上面第5條陳述嗎?
如果要編譯該語句4,則聲明操作符,例如
const X& operator+ (int m) const;
問題是在此語句中
a = b + c + 5;
b + c是一個const對象。 請參閱相應的運算符聲明
const X& operator+ (const X& rhs) const;
您可能不會為const對象調用非const成員函數。
考慮到加法運算符+從左到右分組。 從C ++標准(5.7加法運算符)開始
1加法運算符+和-從左到右分組。
陳述5
(c = a + a) = b + c; //statement 5
則它具有未定義的行為,因為賦值運算符的操作數的評估未排序。 因此,將首先評估表達式(c = a + a),然后評估表達式b + c。 否則首先將評估表達式b + c,然后才評估表達式(c = a + a)
a = b + c + 5;
您的operator +(int m)
未標記為const
。 那就是編譯器錯誤告訴您的。 您還應該僅返回X
因為+
計算新的X值。
X operator+ (int m) const;
會解決的。
僅運算符=是右關聯的。 http://en.cppreference.com/w/cpp/language/operator_precedence
您的陳述1
a.operator =(a.operator +(5.operator +(C)));
我相信這應該拋出錯誤,因為沒有定義的構造函數支持
這里沒有構造函數。
聲明4
a.operator =(b.operator +(c.operator +(5)));
應該
a.operator =(b.operator +(C)+ .operator(5))
聲明5
(c = a + a)= b + c;
由於賦值在括號內,因此優先於關聯性。 即c = a + a
在= b + c
之前求值。
(c.operator =(a.operator +(a)).operator =(b.operator +(c))
語句1這樣做:
a.operator+(5).operator+(c)
這是可行的,因為采用X
的operator+
是const
,因此對a.operator+(5)
返回的const
臨時a.operator+(5)
。
語句4這樣做:
b.operator+(c).operator+(5)
這不起作用,因為采用int
的operator+
不是const
,因此不適用於b.operator+(c)
返回的const
臨時b.operator+(c)
。
這兩個operator+
必須為const
才能實現:
X operator+(const X& rhs) const;
X operator+(const int& m) const;
注意,我還將操作符更改為按值而不是引用返回。 那就是應該的樣子(兩個數字相加的結果畢竟是一個新數字)。
語句一等效於a.operator=(a.operator+(5).operator+(c));
這是完全正確的。
但是,對於語句4, operator+ (int m)
方法必須為const。 含義: const X& operator+ (int m) const;
語句5應該等效於: c.operator=(a.operator+(a)).operator=(b.operator+(c));
編譯代碼時clang的錯誤和警告非常有用,我建議將其用於此類實驗。 它的錯誤和警告消息非常好:
test.cpp:15:13: error: invalid operands to binary expression ('const X' and 'int')
a = b + c + 5; //statement 4 /*compiler Error thrown -
~~~~~ ^ ~
test.cpp:4:12: note: candidate function not viable: no known conversion from 'int' to 'const X' for 1st
argument
const X& operator+ (const X& rhs) const;
^
test.cpp:5:12: note: candidate function not viable: 'this' argument has type 'const X', but method is not
marked const
const X& operator+ (int m);
^
1 error generated.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.