Bit shift operators for IO
suggest changeThe operators << and >> are commonly used as “write” and “read” operators:
std::ostreamoverloads<<to write variables to the underlying stream (example:std::cout)std::istreamoverloads>>to read from the underlying stream to a variable (example:std::cin)
For a user-defined type the overload is a non-member, because the left operand is the stream, not your type. The two operands have different types:
- The return type is a reference to the stream (for example
std::ostream&), so calls can be chained (std::cout << a << b). lhshas that same stream type.rhsis the type you want to print (for exampleT), passed byconst&so a large object is not copied. The operator should not modify it. Example:const Vector&.
Example:
// Overload operator<< so a Vector can be written to an std::ostream.
std::ostream& operator<<(std::ostream& lhs, const Vector& rhs)
{
lhs << "x: " << rhs.x << " y: " << rhs.y << " z: " << rhs.z << '\n';
return lhs;
}
Vector v = { 1, 2, 3};
//Now you can do
std::cout << v;
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents