...有沒有一些實踐時何價值或通過引用返回,當重載操作符?
是的,有一些規範形式found here。它們並不都具有相同的形式 - 它們因操作員而異。一般的建議是遵循內置類型的語義。與所有函數一樣,通用規則仍然適用,例如不返回對局部變量的引用(如OP所示)。
E.g. (在上面的鏈接中找到)給出了問題的添加操作符;
class X
{
public:
X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
{ // but often is, to modify the private members)
/* addition of rhs to *this takes place here */
return *this; // return the result by reference
}
// friends defined inside class body are inline and are hidden from non-ADL lookup
friend X operator+(X lhs, // passing lhs by value helps optimize chained a+b+c
const X& rhs) // otherwise, both parameters may be const references
{
lhs += rhs; // reuse compound assignment
return lhs; // return the result by value (uses move constructor)
}
};
的operator+
是非成員方法(常作爲friend
),並返回由值 - 這對應於內建類型的語義。同樣,operator+=
是成員方法,通過引用返回(*this
的更新版本)。
...當返回相同的對象(*this
)時,正在被返回的同一對象上被引用。有人能解釋爲什麼這樣嗎?
如果返回類型是按值(X operator+
),然後return *this;
意味着當前對象的副本(什麼是this
指出)且已返回。
如果返回類型是按引用(X& operator+
),然後return *this;
意味着當前對象的引用(什麼是this
指向)返回(即,不是一個副本)。
you mean like obj = obj1 + obj2 + obj3; ? –
第一個例子是錯誤的,不要通過引用返回一個局部變量。 – masterxilo