C ++中的重载+运算符在同一条语句中多次

问题描述 投票:0回答:1

我有以下代码在C ++中重载+运算符,当程序执行时,它可以正常工作。我有一个问题:在主函数中,当我重新编写语句以从“ res = t + t1 + t2”(工作正常)到“ res = t +(t1 + t2)”调用重载+运算符时(现在不起作用)。有人可以提供给我解决方案以及原因吗?

已经找到的解决方案是将+函数的签名从“测试运算符+(Test&a)”更新为“测试运算符+(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;    
}
c++ operator-overloading
1个回答
0
投票

问题是您接受的对象是引用,而不是const引用。

Test返回的operator+()是临时的。 Non-const references can't bind to a temporary

这可能之前起作用的原因是+从左到右执行-看起来像这样:

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对象。

© www.soinside.com 2019 - 2024. All rights reserved.