Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: C++
Posted by: Jose Fernando Lopez Fernandez
Added: May 31, 2018 1:48 AM
Views: 13
Minimal example of a simple Point class that overloads the output stream operator (<<).
  1.  
  2. #include <iostream>
  3.  
  4. class Point {
  5.     double m_x;
  6.     double m_y;
  7.     double m_z;
  8.    
  9. public:
  10.     Point()
  11.         : m_x(0), m_y(0), m_z(0)
  12.     { /** Default constructor */ }
  13.    
  14.     Point(const double a, const double b, const double c)
  15.         : m_x(a), m_y(b), m_z(c)
  16.     { /** ... */ }
  17.    
  18.     double x() const noexcept { return m_x; }
  19.     double y() const noexcept { return m_y; }
  20.     double z() const noexcept { return m_z; }
  21.    
  22.     friend std::ostream& operator<<(std::ostream& outputStream, const Point& p)
  23.     {
  24.         return outputStream << "(" << p.x() << "," << p.y() << "," << p.z() << ")";
  25.     }
  26. };
  27.  
  28. int main()
  29. {
  30.     Point origin { 0, 0, 0 };
  31.    
  32.     std::cout << "Origin: " << origin << '\n';
  33. }
  34.