2016-11-03 109 views
9
class A { 
public: 
    string operator+(const A& rhs) { 
     return "this and A&"; 
    } 
}; 

string operator+(const A& lhs, const A& rhs) { 
    return "A& and A&"; 
} 

string operator-(const A& lhs, const A& rhs) { 
    return "A& and A&"; 
} 

int main() { 
    A a; 
    cout << "a+a = " << a + a << endl; 
    cout << "a-a = " << a - a << endl; 
    return 0; 
} 

//output 
a+a = this and A& 
a-a = A& and A& 

我很好奇爲什麼類中的運算符被調用而不是外部調用。運營商之間是否有某種優先權?班上的操作員如何工作?

+4

在幾個同名的函數中進行選擇的過程稱爲*重載分辨率*。在此代碼中,該成員是首選的,因爲非成員需要進行資格轉換(將'const'添加到'lhs'),但成員不需要。如果你創建了成員函數'const'(你應該這樣做,因爲它不修改'* this'),那麼它就會變得模糊 –

回答

4

選擇之中同名的幾個功能的過程稱爲重載。在此代碼中,該成員是首選的,因爲非成員需要進行資格轉換(將const添加到lhs),但該成員不需要。如果你的成員函數爲const(你應該這樣做,因爲它不會修改*this),那麼它就不明確了。

1

每當你的對象是非const的時候,非const的優先級就是const。當左邊是非常量時,內部將被調用,當左邊是常量時,外部將被調用。

見當內被定義爲發生的事情:

string operator+(const A& rhs) const;

+1

「有一個非常量優先於常量。」不在一般情況下。如果'a'被聲明爲'const A a'',則會使用超類超載。 – Angew

+0

這就是我寫的。 – Shloim

+1

答案的寫法是「非常量優先於常量」,這聽起來就像一般性陳述。這當然是不正確的。 – Angew