我有以下代码可重载operator+
,该代码在执行程序时可以正常工作。
在main()
函数中,当我重新编写语句以从operator+
到res= t + t1 + t2
正常工作的res = t + (t1 + t2)
调用重载的operator+
时,它不起作用不再。谁能提供我解决方案以及原因?
已经找到的解决方案是将Test operator +(Test &a)
的签名从Test operator +(const Test &a)
更新为const
。在这里,我在参数列表中使用了#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(int v)
{
num = v;
}
Test operator+(Test &a)
{
Test r(0);
r = num + a.num;
return r;
}
void show()
{
cout << "\n num = " << num;
}
};
int main()
{
Test t(10);
Test t1(20);
Test t2(60);
Test res(0);
res = t + t1 + t2;
res.show();
return 0;
}
关键字。
require(dplyr)
require(tidyr)
New_Trial <- Trial %>%
gather( "site_id","number_visitors", contains("Site") )
答案 0 :(得分:3)
问题是您通过非常量引用而不是const
引用接受对象。
Test
返回的operator+()
对象是临时的。 A non-const reference can't bind to a temporary。
之所以可能在此之前起作用,是因为operator+
从左到右执行-看起来像这样:
object + object + object
temporary + object
临时项仍然具有功能operator+()
,因此仍可以调用它。
另一方面,当您使用括号时,其执行方式如下:
object + object + object
object + temporary
这意味着该临时文件以a
结尾,再次由于上述原因而无法发生。
要解决此问题,请a)将其转换为const
引用,或b)按值传递(不建议这样做,因为它会在您不需要的内存中创建额外的副本):
// a
Test operator +(const Test &a)
// b
Test operator +(Test a)
我也强烈建议也将此功能设为const
:
// a
Test operator +(const Test &a) const
// b
Test operator +(Test a) const
现在,即使它们也位于右侧,您也可以添加const
个对象。
答案 1 :(得分:1)
(t1 + t2)
计算为右值表达式。
但是您的operator+(&)
只能绑定到非常量左值。另一方面,const &
可以绑定到左值和右值,因此operator+(const &)
可以工作。