mercredi 27 juin 2018

Why I get this error "invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'"

Given the following code:

#include <iostream>
using std::ostream;

class A {
    int x;
public:
    A(int x) :
            x(x) {
    }
    A& operator+=(const A& a) {
        this->x = this->x + a.x;
        return *this;
    }
    friend ostream& operator<<(ostream& os, const A& a);

};

A operator+(const A& a1, const A& a2) {
    return A(a1) + a2;
}

ostream& operator<<(ostream& os, const A& a) {
    return os << a.x;
}

int main() {
    const A a1(2);
    A& sum = a1 + a1; // error**************
    std::cout << sum;
}

I get the following error:

invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'

But I don't understand what is the reason of this error. At all, I get new object from operator+ and I define a reference (sum) to this object , so what is the problem in this way? And how can I fix it?

Aucun commentaire:

Enregistrer un commentaire