...有没有一些实践时何价值或通过引用返回,当重载操作符?
是的,有一些规范形式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