运算符重载错误:无法将“some-type”类型的非常量左值引用绑定到“some-type”类型的右值

问题描述

function createLink(object) {
return `<a href="${object.DetailActionUri}">Detail</a>`;
}

编译器输出

#include <iostream>
#include <string>

using namespace std;

namespace ComplexnumberNamespace
{
    typedef struct _Data
    {
        double real;
        double imag;
    }Data;

    class Complexnumber
    {
    private:
        Data data{};
    public:
        Complexnumber();
        Complexnumber(float real,float imag);
        Complexnumber(Complexnumber&);
        string to_string();
        void operator = (Complexnumber&);
        Complexnumber operator + (Complexnumber& rhs);
    };

    string Complexnumber::to_string() {
        std::string str;
        str = std::to_string(data.real);
        str.append(" + i ");
        str.append(std::to_string(data.imag));

        return str;
    }

    Complexnumber::Complexnumber(Complexnumber & rhs) {
        std::cout<<"copy constructor";
        data.real = rhs.data.real;
        data.imag = rhs.data.imag;
    }

    Complexnumber::Complexnumber() {
        data.real = 0.0;
        data.imag = 0.0;
    }

    void Complexnumber::operator=(Complexnumber &cplx) {
        std::cout<<"assignment operator";
        data.real = cplx.data.real;
        data.imag = cplx.data.imag;
    }

    Complexnumber::Complexnumber(float real,float imag) {
        data.real = real;
        data.imag = imag;
    }

    Complexnumber Complexnumber::operator+(Complexnumber &rhs)
    {
        Complexnumber temp(data.real + rhs.data.real,data.imag+rhs.data.imag);

        return temp;
    }
}

using namespace ComplexnumberNamespace;

int main()
{
    Complexnumber c1(1,2);

    Complexnumber c2(4,3);

    Complexnumber sum = c1 + c2;

    std::cout<<sum.to_string();
}

为什么我的源代码会产生这个错误

我做错了什么?

我该如何解决这个问题?

解决方法

ComplexNumber& 作为参数的构造函数和运算符重载需要改为使用 const ComplexNumber&

这一行 ComplexNumber sum = c1 + c2 实际上调用了您的 ComplexNumber 复制构造函数,并为它提供了 c1 + c2 表达式结果,这是一个临时的 ComplexNumber。由于您无法在 C++ 中对临时对象进行非常量引用,因此会出现此错误。

理想情况下,您的 ComplexNumber 类应如下所示:

struct ComplexNumber {

  // ...

  // Copy 
  ComplexNumber(const ComplexNumber& other) { *this = other; } 
  ComplexNumber& operator=(const ComplexNumber& other) {
    if (this != &other) { /* copy your attributes from other to this */ }
    return *this;
  }

  // Move (optional - and not really useful in your case)
  ComplexNumber(ComplexNumber&& other);
  ComplexNumber& operator=(ComplexNumber&& other);

  // Unlike operator= we return a temporary value,// so it's a ComplexNumber indeed (no &)
  // We'll modify neither 'this' nor 'rhs',so mark them const
  ComplexNumber operator+(const ComplexNumber& rhs) const;

  ~ComplexNumber();
};

更多详情:https://en.cppreference.com/w/cpp/language/rule_of_three


一些提示:

  • 不要将 using namespace std 放在标题中(我猜是标题)
  • typedef struct _Data { ... } Data; 是旧的 C 符号。您可以简单地使用 struct Type { ... } myObj;