| CARVIEW |
Select Language
HTTP/2 200
date: Tue, 30 Dec 2025 18:09:04 GMT
content-type: text/html; charset=utf-8
server: cloudflare
last-modified: Mon, 05 Jul 2021 23:22:32 GMT
vary: Accept-Encoding
access-control-allow-origin: *
nel: {"report_to":"cf-nel","success_fraction":0.0,"max_age":604800}
expires: Tue, 30 Dec 2025 18:19:04 GMT
cache-control: max-age=600
report-to: {"group":"cf-nel","max_age":604800,"endpoints":[{"url":"https://a.nel.cloudflare.com/report/v4?s=GGna3rP4RG3UO3k%2BbpCIztlph5FkWfuSKqG5%2FM5ANlXBKqPOaQaaw2MzxuKsKwpRlO4mhwV3yeDw%2FrXluqldecrhTZah7IZMHnTYhiSYsw%3D%3D"}]}
x-proxy-cache: MISS
x-github-request-id: 2A34:299655:15D3F8C:1789132:6954153F
cf-cache-status: DYNAMIC
content-encoding: gzip
cf-ray: 9b637c6d3c6cff68-BOM
alt-svc: h3=":443"; ma=86400
Overload operator<< - C++ Patterns
← 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.