C++ 有人能解释一下为什么';让我们来纠正错误吧?类型为';的非常量引用的初始化无效;百安居酒店';从类型为';B';?

C++ 有人能解释一下为什么';让我们来纠正错误吧?类型为';的非常量引用的初始化无效;百安居酒店';从类型为';B';?,c++,C++,给定以下代码: #include <iostream> using namespace std; class B { private: int n; public: B(int x) : n(x) { } B operator+(B& b) { return B(n + b.n); } friend ostream& operator<<(ostream &o

给定以下代码:

#include <iostream>
using namespace std;

class B {
private:
    int n;
public:
    B(int x) :
            n(x) {
    }
    B operator+(B& b) {
        return B(n + b.n);
    }
    friend ostream& operator<<(ostream &out, const B& b) {
        out << "B: " << b.n;
        return out;
    }
    bool operator<(const B& rhs) const {
        return n < rhs.n;
    }
};

int main() {
    B b1(1), b2(2), b3(3);
    const B b4 = b1 + (b2 + b3); // error
    cout << b4 << b1 << b2 << b3;
    return 0;
}
致:

所以一切都会好起来的。但是,为什么真的要修复它呢

从“B”类型的右值初始化“B&”类型的非常量引用无效

(我理解错误的含义,但是,我不明白为什么更改会修复错误)


此外,上面的代码(给我错误)与下面的代码有什么区别:

class D: public B {
    double m;
public:
    D() :
            B(0), m(0) {
    }
    D(int x, int y) :
            B(x), m(y) {
    }
    D operator+(D& d) { // ~~
        return d;
    }
    friend ostream& operator<<(ostream &out, const D& d) {
        out << static_cast<const B&>(d);
        out << ", D: " << d.m;
        return out;
    }
};

int main() {
    B b4(4);
    D d1(1, 0), d2(1, 2);
    D d3 = d1 + d2;
    cout << b4 << ", " << d3 << endl;
    return 0;
}
D类:公共B类{
双m;
公众:
D():
B(0),m(0){
}
D(整数x,整数y):
B(x),m(y){
}
D运算符+(D&D){//~~
返回d;
}

朋友OsFrand和OffATORI建议您从C++中学习不同的代码开始。因为<代码>操作符+()/CUT>返回一个值,并接受非代码> const 参考。
无法绑定到非
常量
引用,但正在通过非
常量
引用传递,以便将其添加到
b1
。简单的错误修复方法:将
B操作符+(B&B)
更改为
B操作符+(常量B&B)const
const
将确保引用值的生存期。相关:可能重复
B operator+(const B& b)
class D: public B {
    double m;
public:
    D() :
            B(0), m(0) {
    }
    D(int x, int y) :
            B(x), m(y) {
    }
    D operator+(D& d) { // ~~
        return d;
    }
    friend ostream& operator<<(ostream &out, const D& d) {
        out << static_cast<const B&>(d);
        out << ", D: " << d.m;
        return out;
    }
};

int main() {
    B b4(4);
    D d1(1, 0), d2(1, 2);
    D d3 = d1 + d2;
    cout << b4 << ", " << d3 << endl;
    return 0;
}