简体   繁体   中英

C++: Need help understanding operator-overloading error

I got this code:

1 #include <iostream>
2 using namespace std;
3
4 class B {
5 private:
6      int n;
7 public:
8      B(int x) : n(x) {}
9      B operator +(B& b) {
10         return B(n+b.n);
11     }
12     friend ostream& operator <<(ostream &out, const B& b) {
13         out << "B: " << b.n;
14         return out;
15     }
16     bool operator <(const B& rhs) const{
17         return n < rhs.n;
18     }
19 };
20
21 B smaller (const B& b1, const B& b2) {
22     if(b1 < b2)
23         return b1;
24     else
25         return b2;
26 }
27
28 int main() {
29     B b1(1), b2(2), b3(3);
30     const B b4 = b1 + (b2 + b3);
31     cout << smaller(b1,b2) << endl;
32     return 0;
33 }

I was asked to point out the errors (explain them) and supply a fix, after finding two and fixing them I got the above code.

When trying to compile it on Visual Code I noticed that line 30 is giving out an error without me understanding why. The error I got was:

no match for 'operator+' (operand types are 'B' and 'B')

and

cannot bind non-const lvalue reference of type 'B&' to an rvalue of type 'B'

After searching on google and finding nothing I tried varius things including adding a const to the parameter in line 9 (operator +) which fixed the problem. I still dont understand what was the problem and I would like to get an explanation.

thank you.

The result of (b2 + b3) is a temporary . That is it's an object of type B that is created and destroyed as part of executing the larger expression.

C++ has a rule that you cannot bind a non-const reference to a temporary. But that is exactly what your code was trying to do. Hence the need for const.

Incidentally the correct signature for your overloaded operator is

class B
{
    B operator +(const B& b) const {
        ...
    }
};

Both the method and the parameter should be const.

Even better would be to make operator+ a non-member

B operator +(const B& a, const B& b) {
    ...
}

Some more reading .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM