4

我看过很多教程,并试图在 stackoverflow 上找到答案,但没有成功。

我不确定的是;在重载运算符时,是否有一些实践何时按值或按引用返回?

例如

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

或相同的东西,但按价值

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

我想提一下,我注意到,在几乎 90% 的情况下,当返回同一个对象 ( *this) 时,会在返回的同一个对象上引用。有人可以解释为什么会这样吗?

4

2 回答 2

3

按引用返回的第一个选项operator+是错误的,因为您是按引用返回本地对象,但是在运算符函数体结束后本地对象不再存在。一般来说:

  • 变异运算符喜欢+=-=按引用返回,因为它们返回变异对象本身(通过return *this;:)
  • 普通运算符喜欢+-应该按值返回,因为需要构造一个新对象来保存结果。
于 2016-04-28T07:59:03.707 回答
3

...当重载运算符时,是否有一些实践何时按值或按引用返回?

是的,这里有一些规范形式。它们并非都具有相同的形式 - 它们因运营商而异。一般建议是遵循内置类型的语义。与所有函数一样,一般规则仍然适用,例如不返回对局部变量的引用(如 OP 中所示)。

例如(在上面的链接中找到)给定问题的加法运算符;

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+是一个非成员方法(通常作为 a friend)并按值返回 - 这对应于内置类型的语义。类似地,operator+=是成员方法并通过引用返回(的更新版本*this)。

...当返回相同的对象 ( *this) 时,被返回的相同对象引用。有人可以解释为什么会这样吗?

如果返回类型是按值 ( X operator+),则return *this;意味着this制作并返回当前对象(由 指向的对象)的副本。

如果返回类型是按引用 ( X& operator+),则return *this;意味着返回对当前对象(由 指向的对象)的引用this(即不是副本)。

于 2016-04-28T07:58:21.657 回答