0

我见过很多教程,并试图在stackoverflow上找到答案,但没有成功。运算符重载C++参考或值

我不确定的是;有没有什么时候通过价值或通过引用返回,当超载运营商?

例如,

Class &operator+(){ 
    Class obj; 
    //... 
    return obj; 
} 

或相同的事情,但按价值

Class operator+(){ 
    Class obj; 
    //... 
    return obj; 
} 

而且我想提,我注意到,在返回相同的对象(*this)时的病例近90%,是在返回的同一个对象上被引用。有人能解释为什么这样吗?

+0

you mean like obj = obj1 + obj2 + obj3; ? –

+0

第一个例子是错误的,不要通过引用返回一个局部变量。 – masterxilo

回答

2

...有没有一些实践时何价值或通过引用返回,当重载操作符?

是的,有一些规范形式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指向)返回(即,不是一个副本)。

+0

所以基本上我需要返回相同的对象的引用,如果我想做链加法?没有其他区别只返回*这个? –

+0

它会创建'* this'的副本。 – Niall

1

通过引用从operator+返回的第一个选项是错误的,因为您通过引用返回本地对象,但本地对象在操作符函数体结束后不再存在。一般:

  • 变异的运营商如+=-=返回引用,因为它们返回的突变对象本身(作者:return *this;
  • 普通运营商如+-应该由价值回归,因为一个新的对象需要被构建来保持结果。