A custom inserter (<<) : custom inserter « Operator Overloading « C++ Tutorial






#include <iostream> 
using namespace std; 
 
class MyClass { 
public: 
  int x, y, z;
  MyClass(int a, int b, int c) { x = a; y = b; z = c; } 
}; 
 
// Display X, Y, Z coordinates - MyClass inserter. 
ostream &operator<<(ostream &stream, MyClass obj) 
{ 
  stream << obj.x << ", "; 
  stream << obj.y << ", "; 
  stream << obj.z << "\n"; 
  return stream;  // return the stream 
} 
 
int main() 
{ 
  MyClass a(1, 2, 3), b(3, 4, 5), c(5, 6, 7); 
 
  cout << a << b << c; 
 
  return 0; 
}
1, 2, 3
3, 4, 5
5, 6, 7








10.20.custom inserter
10.20.1.A custom inserter (<<)
10.20.2.Use a friend to overload <<