I overloaded "<<" and it works fine, the same for "+=", but they won't work together. I don't get why, += returns a foo& object, just like "++" which works fine. I see that something like int x; cout<<x+=1;
doesn't work too, but I don't think that explains why my code shouldn't work, after all it's pretty much the same as "++", it has the same type of return.
Here is my code:
#include <iostream>
using namespace std;
class foo
{
int x;
public:
foo()
{
x=10;
}
foo(const foo& f1)
{
this->x=f1.x;
cout<<"OK"; /// testing if it really works
}
foo& operator ++ ()
{
++x;
return *this;
}
foo& operator ++ (int)
{
x++;
return *this;
}
foo& operator+=(const int& value)
{
x=x+value;
return *this;
}
friend istream& operator>>(istream& in, foo& S);
friend ostream& operator<<(ostream& out, const foo& S);
};
istream& operator>>(istream& in, foo& S)
{
in>>S.x;
return in;
}
ostream& operator<<(ostream& out, const foo& S)
{
out<<S.x;
return out;
}
int main()
{
foo A, B, C;
cout<<B++; /// works fine, prints 11
C+=20;
cout<<C; /// works fine, prints 30
cout<<A+=99; ///error: no match for 'operator+=' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'int')
return 0;
}