← Patterns
Overload operator<<
1234567891011121314151617 | #include <iostream>
class foo
{
public:
friend std::ostream& operator<<(std::ostream& stream,
foo const& f);
private:
int x = 10;
};
std::ostream& operator<<(std::ostream& stream,
foo const& f)
{
return stream << "A foo with x = " << f.x;
} |
This pattern is licensed under the CC0 Public Domain Dedication.
Requires
c++98
or newer.
Intent
Write your class type objects to an output stream.
Description
We implement operator<<
on lines 13–17, which takes a reference to an
std::ostream
(the base class for all
output streams) and the foo
object we wish to write to the stream.
On line 16, we simply write a string representing the foo
object to
the steam and return a reference to the stream itself, allowing
this call to be chained.
Note that we declare this operator<<
as a friend
of foo
on
lines 6–7. This gives it access to foo
’s private member, x
.