#include<iostream>
using namespace std;
class test
{
int i;
string s;
public:
test(){}
test(int a,string b)
{
i=a;
s=b;
}
void operator = (test &temp)
{
cout<<"In assignment operator"<<endl;
i=temp.i;
s=temp.s;
}
test operator + (test &temp)
{
test newobj;
newobj.i=i+temp.i;
newobj.s=s+" "+temp.s;
return newobj;
}
};
main()
{
test t1(5,"ABC");
test t2;
t2=t1;
test t3;
t3=t1+t2;
}
问题:t3=t1+t2
给我一个错误。我想重载 = 和 + 运算符并如上所示使用它们。我哪里错了?我想显式定义一个赋值运算符重载,即使编译器提供了一个。
error : invalid initialization of non-const reference of type ‘test&’ from an rvalue of type ‘
test
’t3=t1+t2;
initializing argument 1 of ‘
void test::operator=(test&)
’void operator = (test &temp)
最佳答案
t1+t2
返回一个临时的 test
,它不能绑定(bind)到对非常量的引用(即 test &
),这就是 t3=t1+t2;
失败的原因。另一方面,temporary 可以绑定(bind)到对 const 的引用(即 const test&
)。所以你可以把参数类型改成const test&
,例如
void operator = (const test &temp)
{
cout<<"In assignment operator"<<endl;
i=temp.i;
s=temp.s;
}
顺便说一句:最好用 operator+
做同样的事情。
BTW2:operator=
的常规签名(和实现)是:
test& operator= (const test& temp)
{
cout<<"In assignment operator"<<endl;
i = temp.i;
s = temp.s;
return *this;
}
关于c++ - 重载赋值和加运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44300010/