【问题标题】:Overloading augmented assignment in c++ (return type) [duplicate]在c ++中重载增强赋值(返回类型)[重复]
【发布时间】:2016-02-29 10:35:46
【问题描述】:

我正在制作一个使用 += 操作的对象。重载应该返回对*this 的引用还是应该只返回*this

【问题讨论】:

  • 我不明白这个问题
  • @bath 我正要结束这个问题,因为它是同一个问题的副本。我看到你重新打开了它。你不同意它是重复的吗?您准备发布史诗般的答案吗?
  • 我重新打开了,因为建议的副本对于这样一个尖锐的问题来说太宽泛了。

标签: c++ c++11 operator-overloading


【解决方案1】:

http://en.cppreference.com/w/cpp/language/operators

在那里你可以找到规范的实现

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)
  }
};

【讨论】:

    【解决方案2】:

    假设foobarFoo 的实例。

    如果+=没有返回引用,则表达式

    foo += bar += bar

    将在语法上无效,这将背离内置类型(尽管有趣的是,内置类型的此类表达式的行为未定义,因为 += 不是此类类型的排序点.).

    不返回引用也可能导致更多地使用 Foo 的复制构造函数。

    快速回答:返回非const 引用。

    【讨论】:

      猜你喜欢
      • 2012-04-26
      • 2011-01-17
      • 2017-06-20
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多