Given the following error:
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(2);
B b2(3);
B res121 = b1 + (b2 + b1); // ----error
B res21 = b2 + b1;
B res1_21 = b1 + res21; // ---- No error
cout << res1_21;
return 0;
}
Why I get error while I try to define res121
but don't get error while I try to define res1_21
?
After all, b2+b1
is object in type of B
, so what is the problem? What it's say that it's a temporary object
, how can I know what is temporary object
and what it's not.