用戶定義類型中,x = x + y 與 x += y 無自動關聯。**三大運算符(+、=、+=)互不相關,需手動實現一致性**。
class Rational {
public:
Rational& operator+=(const Rational& rhs);
Rational& operator-=(const Rational& rhs);
};
const Rational operator+(const Rational& lhs, const Rational& rhs) {
return Rational(lhs) += rhs;
}
const Rational operator-(const Rational& lhs, const Rational& rhs) {
return Rational(lhs) -= rhs;
}
優勢:
+=/-=,單獨形式自動一致;
template<class T> const T operator+(const T& lhs, const T& rhs) {
return T(lhs) += rhs;
}
result = a + b + c + d(易讀、可接受 80% 場景)vs result=a; result+=b; ...(極致效能)。語義保持一致。return T(lhs) += rhs;(臨時對象)比 T result(lhs); return result += rhs;(命名對象)更易觸發編譯器**返回值優化 (RVO)**,尤其舊編譯器下更優。雖兩者開銷相近,未命名對象歷史上更易優化。庫設計者雙提供、應用開發者效能優先用賦值形式。**賦值形式是基石,單獨形式是語法糖**——守住這原則,代碼才健壯高效。