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:
Code:
Simple operator+(const Simple& rhs) {return Simple(n + rhs.n);}
I've also overloaded the += operator and it returns a reference to the modified object:
Code:
Simple& operator +=(const Simple& rhs)
{
n += rhs.n;
return *this;
}
And the << operator is overloaded like so:
Code:
friend ostream&
operator<<(ostream& os, const Simple& cs)
{
return os << "Object: n = " << cs.n << endl;
}
My problem: I can do this....
Code:
Simple s1(15), s2(20);
cout << s1 + s2;
But if I do this...
I get the following error:
Code:
binary '+=' : 'std::ostream' does not define this operator
or a conversion to a type acceptable to the predefined operator
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?