簡體   English   中英

是在C ++中獨立定義的算術/賦值運算符和復合賦值運算符

[英]Are arithmetic/assignment operators and compound assignment operators independently defined in C++

即如果在類定義中我重載了operator+operator= ,這對operator+=有影響嗎? 反之亦然。

除非另有定義,否則這些運算符是否完全獨立?

不,這些操作員是完全獨立的。

您當然可以使用其他實現,但默認情況下它們是獨立的。

struct X
{
    X& operator = (const X&);
    X operator + (const X&) const;
    //X& operator += (const X& other) 
    //        { operator=(operator+(other)); return *this; }
};

X x, y;
x += y; //doesn't compile unless you uncomment that line

語言對此沒有任何限制-您可以有一個運算符+來對兩個對象求和,而+ =可以炸毀太陽,這仍然是合法的。 另一方面,強烈建議不要提出違反直覺的運算符重載,否則您的類將導致使用時極為尷尬。

順便說一句,為了避免代碼重復,通常以+ =的形式實現+:

A operator+(const A& right) const
{
    A ret(*this);
    ret+=right;
    return ret;
} 

不,如果您的行為是這樣,則還需要重寫+=運算符!

暫無
暫無

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

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