Demonstrate a custom inserter and extractor for objects of type ThreeD. : Inserter Extractor « Overload « C++






Demonstrate a custom inserter and extractor for objects of type ThreeD.

  
#include <iostream>

using namespace std;

class ThreeD {
  int x, y, z;
public:
  ThreeD(int a, int b, int c) { x = a; y = b; z = c; }

  // Make the inserter and extractor friends of ThreeD.
  friend ostream &operator<<(ostream &stream, const ThreeD &obj);
  friend istream &operator>>(istream &stream, ThreeD &obj);

};

// ThreeD inserter. Display the X, Y, Z coordinates.
ostream &operator<<(ostream &stream, const ThreeD &obj)
{
  stream << obj.x << ", ";
  stream << obj.y << ", ";
  stream << obj.z << "\n";
  return stream;
}

// ThreeD extractor. Get three-dimensional values.
istream &operator>>(istream &stream, ThreeD &obj)
{
  stream >> obj.x >> obj.y >> obj.z;
  return stream;
}

int main()
{
  ThreeD td(1, 2, 3);

  cout << "The coordinates in td: " << td << endl;

  cout << "Enter new three-d coordinates: ";
  cin >> td;
  cout << "The coordinates in td are now: " << td << endl;

  return 0;
}
  
    
  








Related examples in the same category

1.Overload ostream and istreamOverload ostream and istream
2.Overload the << operator
3.Override and input output stream operator
4.Overloading operator<<()
5.Non-member functions are used to create custom inserters for three_d objects and to overload + for int + three_d.