#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
给了我一个错误。我想重载=和+运算符并使用它们,如上所示。我哪里错了?我想明确定义一个赋值运算符重载,即使编译器提供了一个。
错误:从'
类型的右值开始无效初始化'test&amp;'类型的非const引用test
't3=t1+t2;
初始化“
void test::operator=(test&)
”的参数1void operator = (test &temp)
答案 0 :(得分:1)
t1+t2
返回一个临时test
,它不能绑定引用非const(即test &
),这就是t3=t1+t2;
失败的原因。另一方面,临时可以绑定引用const(即const test&
)。因此,您可以将参数类型更改为const test&
,例如
void operator = (const test &temp)
{
cout<<"In assignment operator"<<endl;
i=temp.i;
s=temp.s;
}
BTW1:最好用operator+
做同样的事情。
BTW2:operator=
的传统签名(和实现)是:
test& operator= (const test& temp)
{
cout<<"In assignment operator"<<endl;
i = temp.i;
s = temp.s;
return *this;
}