[英]implicit assignment operators [C++]
如果我在類上有運算符重載,那么是否隱式創建了運算符的賦值版本?
class square{
square operator+(const square& B);
void operator=(const square& B);
};
這樣,我可以打電話嗎
square A, B;
A += B;
編譯器隱式決定先調用“ operator +”,再調用“ operator =”?
不, +=
必須明確定義。
附帶說明, operator+
通常應創建一個新對象 :
square operator+(const square& B);
並且operator=
應該返回對*this
的引用 :
square& operator=(const square& B);
同樣值得注意的是, operator+
通常是根據operator+=
,即operator+
在新副本上調用operator+=
。
不,運算符不是隱式定義的。 但是, boost/operators.hpp
定義了有用的幫助程序模板,以避免樣板代碼。 他們的文檔中的示例:
例如,如果您聲明這樣的類:
class MyInt
: boost::operators<MyInt> {
bool operator<(const MyInt& x) const;
bool operator==(const MyInt& x) const;
MyInt& operator+=(const MyInt& x);
MyInt& operator-=(const MyInt& x);
MyInt& operator*=(const MyInt& x);
MyInt& operator/=(const MyInt& x);
MyInt& operator%=(const MyInt& x);
MyInt& operator|=(const MyInt& x);
MyInt& operator&=(const MyInt& x);
MyInt& operator^=(const MyInt& x);
MyInt& operator++();
MyInt& operator--(); };
然后
operators<>
模板添加了十幾個其他運算符,例如operator>
,<=
,>=
和(binary)+
。 還提供了模板的兩個參數形式,以允許與其他類型的交互。
沒有operator+=
是它自己的運算符,必須明確定義。
請注意, operator+
應該返回一個新對象,而不是對原始對象的引用。 原始對象應保持不變。
operator+=
應該返回添加了所需值的原始對象。 通常最好使用operator+=
因為它消除了一個臨時對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.