I've been experimenting with some simple operator overloading. I have a simple class which contains an int. I've overloaded the + operator to add two objects and it returns a new object:
I've also overloaded the += operator and it returns a reference to the modified object:Code:Simple operator+(const Simple& rhs) {return Simple(n + rhs.n);}
And the << operator is overloaded like so:Code:Simple& operator +=(const Simple& rhs) { n += rhs.n; return *this; }
My problem: I can do this....Code:friend ostream& operator<<(ostream& os, const Simple& cs) { return os << "Object: n = " << cs.n << endl; }
But if I do this...Code:Simple s1(15), s2(20); cout << s1 + s2;
I get the following error:Code:cout << s1 += s2;
However, if I use parenthesis, as in cout << (s1 += s2); it works fine, but I can't quite see why. Is it something to do with operator precedence?Code:binary '+=' : 'std::ostream' does not define this operator or a conversion to a type acceptable to the predefined operator



LinkBack URL
About LinkBacks


