An inserter can be used to output data in any form : Inserter « Overload « C++






An inserter can be used to output data in any form

An inserter can be used to output data in any form

#include <iostream>
using namespace std;
class MyClass {
  int x, y;
public:
  MyClass(int i, int j) { 
     x=i; 
     y=j; 
  }
  friend ostream &operator<<(ostream &stream, MyClass o);
};

ostream &operator<<(ostream &stream, MyClass o)
{
  register int i, j;
  for(i=0; i<o.x; i++)
    stream << "*";
  stream << "\n";
  for(j=1; j<o.y-1; j++) {
    for(i=0; i<o.x; i++)
      if(i==0 || i==o.x-1) stream << "*";
      else stream << " ";
    stream << "\n";
  }
  for(i=0; i<o.x; i++)
     stream << "*";
  stream << "\n";
  return stream;
}
int main()
{
  MyClass a(14, 6), b(30, 7), c(40, 5);
  cout << "Here are some:\n";
  cout << a << b << c;
  return 0;
}


           
       








Related examples in the same category

1.Create a non-friend inserter.Create a non-friend inserter.
2.Use a friend inserter for objects of type MyClass.Use a friend inserter for objects of type MyClass.
3.This program draws right trianglesThis program draws right triangles
4.PhoneNumber inserter functionPhoneNumber inserter function
5.Use friend function to operator: <<, >>Use friend function to operator: <<, >>
6.Output account info to a file using an inserter.Output account info to a file using an inserter.