Skip to content

Latest commit

 

History

History
35 lines (27 loc) · 963 Bytes

9.3 — Overloading the IO operators.md

File metadata and controls

35 lines (27 loc) · 963 Bytes

9.3 — Overloading the I/O operators

For classes that have multiple member variables, printing each of the individual variables on the screen can get tiresome fast. For example, consider the following class:

class Point
{
private:
    double m_x{};
    double m_y{};
    double m_z{};
 
public:
    Point(double x=0.0, double y=0.0, double z=0.0)
      : m_x{x}, m_y{y}, m_z{z}
    {
    }
 
    double getX() const { return m_x; }
    double getY() const { return m_y; }
    double getZ() const { return m_z; }
};

If you wanted to print an instance of this class to the screen, you’d have to do something like this:

Point point{5.0, 6.0, 7.0};
 
std::cout << "Point(" << point.getX() << ", " <<
    point.getY() << ", " <<
    point.getZ() << ')';

Of course, it makes more sense to do this as a reusable function. And in previous examples, you’ve seen us create print() functions that work like this: