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.
Aucun commentaire:
Enregistrer un commentaire