cannot bind non-const lvalue reference of type ‘***&‘ to an rvalue of type ‘***‘解决方法

在写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

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值