Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/137.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c+中的重载增广赋值+;(返回类型)_C++_C++11_Operator Overloading - Fatal编程技术网

C++ c+中的重载增广赋值+;(返回类型)

C++ c+中的重载增广赋值+;(返回类型),c++,c++11,operator-overloading,C++,C++11,Operator Overloading,我正在制作一个使用+=运算的对象。重载是否应该返回对*this的引用,还是只返回*this? 在那里你可以找到规范的实现 假设foo和bar是foo的实例 如果+=未返回引用,则表达式 foo+=bar+=bar 将在语法上无效,这将与内置类型不同(尽管有趣的是,内置类型的此类表达式的行为未定义,因为+=不是此类类型的排序点) 不返回引用还可能导致更多地使用Foo的复制构造函数 快速回答:返回一个非常量引用。我不理解question@bath我正要结束这个问题,作为同一个问题的重复。我看到你重新

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

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


假设
foo
bar
foo
的实例

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

foo+=bar+=bar

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

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


快速回答:返回一个非
常量
引用。

我不理解question@bath我正要结束这个问题,作为同一个问题的重复。我看到你重新打开了它。你不同意这是重复的吗?你准备发布一个史诗般的答案吗?我重新打开了,因为提议的副本对于这样一个尖锐的问题来说太宽泛了。
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)
  }
};