toString() method?

IS there any possible way to make the << ( insertion operator) to work with an instance of my class?

I mean, suppose i have a class like this:

1
2
3
4
5
6
7
class Foo
{
     int x;
public:
       Foo ( int x ): x(x) {}
};


and I wanna overload the << operator so that when I write

1
2
3
4
5
6
7
8
int main()
{
Foo myFoo(3);

cout << myFoo << endl;

return 0;
}


I'd get
3
as the output.
Yes, overload the << operator with this signature:

std::ostream& operator << (std::ostream& str, const Foo& f);
Last edited on
Topic archived. No new replies allowed.