通过参考和操作员链接返回

Return by reference and operator chaining

本文关键字:链接 返回 操作员 参考      更新时间:2023-10-16

为什么要返回操作员链接?

我在这样看了很多答案,库存短语是"通过参考返回允许操作员链接",但是没有解释,我不明白为什么我不能以其他方式做。p>例如,这似乎在我的系统上编译并运行良好,链接起作用:

TestClass operator+=(TestClass tc){
    somePrivateValue += tc.somePrivateValue;
    return *this;
}

我也可以做到这一点:

TestClass& operator+=(TestClass& tc){
    somePrivateValue += tc.somePrivateValue;
    return *this;
}

排除第二个示例不需要为TestClass调用复制构造函数的其他优点是什么?

和链接作品

不,不是。

TestClass a = some_value;
TestClass b = some_other_value;
(a += b) += b;

现在检查a的值,但是完成了。它反映了两次被b递增吗?或仅一次?