在写C++作业的时候,我发现使用
#include <iostream>
class complex{
public:
int real;
int imaginary;
public:
complex(){
};
void getreal(int a){
real = a;
}
void getimaginary(int a){
imaginary = a;
}
complex(complex &a){
this->imaginary = a.imaginary;
this->real = a.real;
}
complex& operator=(complex a){
this->imaginary = a.imaginary;
this->real = a.real;
return *this;
}
complex operator+(complex &a){
complex result;
result.real = a.real + this->real;
result.imaginary = a.imaginary + this->imaginary;
return result;
}
};
int main(){
complex a;
a.getimaginary(3);
a.getreal(4);
complex b;
b.getreal(4);
b.getimaginary(17);
complex c;
c = a + b;
return 0;
}
会出现cannot bind non-const lvalue reference of type ‘complex&’ to an rvalue of type 'complex’的错误
出现这个错误的原因是:c++不允许非常量的临时引用作为参数,因为c++认为,非常量的参数进入函数内部就是要做修改的,如果对临时引用进行修改是没有意义的。
上述代码中c = a+b的部分,a+b是一个临时变量。而接下来调用operator=函数中,其参数为变量,因此要在栈区创建并且赋值(调用拷贝函数)一个局部变量a。在调用拷贝函数的时候,会将(a+b)传入拷贝函数的参数,导致以临时变量的形式传入一个函数,因而报错。
解决方法:
将拷贝函数中的参数改为const complex类型
同理:对于a+(b+c)的情况,也要将operator+的参数设置为const