Mega Code Archive

 
Categories / C++ Tutorial / Operator Overloading
 

Class level ostream operator and istream operator

#include<iostream.h> #include<fstream.h> class ThreeD {   int x,y,z; public:   ThreeD(int i,int j,int k){     x=i;     y=j;     z=k;   }   friend ostream& operator<<(ostream& stream,ThreeD ob);   friend istream& operator>>(istream& stream,ThreeD ob); }; ostream& operator<<(ostream& stream,ThreeD ob) {   stream<<ob.x<<' '<<ob.y<<' '<<ob.z<<'\n';   return stream; } istream& operator>>(istream& stream,ThreeD  ob) {   stream>>ob.x>>ob.y>>ob.z;   return stream; } main() {   ThreeD o1(1,2,3),o2(4,5,6);   ofstream out("test");   if(!out)   {     cout<<"Cannot open output file\n";        return 1;   }   cout<<o1<<o2;   out.close();   ifstream in("test");   if(!in)   {     cout<<"Cannot open input file\n";        return 1;   }   ThreeD o3(0,0,0),o4(0,0,0);   in>>o3>>o4;   return 0; } 1 2 3 4 5 6