June 2025
Intermediate to advanced
1093 pages
33h 24m
English
The next step is actually just cosmetic. To output an object to an ostream, there is a commonly used method in practice: overload the operator<< global operator for ostream& and your type.
std::ostream& Person::print(std::ostream& os) { return os << format("{} ({}) from {}", name_, age_, city_);}std::ostream& operator<<(std::ostream& os, Person p) { return p.print(os);}
Listing 12.9 You can overload the standard operator for output.
Instead of calling p.print(), you can also output the fields directly:
std::ostream& operator<<(std::ostream& os, Person p) { return os << format("{} ({}) from {}", p.name_, p.age_, p.city_);}
Did you notice that the return type is not void? By returning the ostream passed as ...
Read now
Unlock full access