Stream Insertion and Extraction Operators
Teach your types to interoperate with std::cout via >.
Why Overload << and >>
Teach your types to interoperate with std::cout and std::cin by overloading the stream operators.
The Insertion Operator <<
Define as a free function taking an output stream by reference. Return the stream to enable chaining.
struct Point { int x, y; };
std::ostream& operator<<(std::ostream& os, const Point& p) {
return os << "(" << p.x << ", " << p.y << ")";
}
Point p{3, 4};
std::cout << p << "\n"; // (3, 4)All lessons in this course
- Arithmetic and Comparison Operators
- Stream Insertion and Extraction Operators
- Subscript and Function Call Operators
- Three-Way Comparison Operator C++20