Stream extraction (>>)
and insertion (<<) operators can be overloaded for read from
keyboard and display the output. input and output to accept the user defined
data. These operator also used for
writing and reading from data files.
Example :
#include
<iostream.h>
//Example of Operator << >>
class
Cal
{
private:
int
a,b,c;
public:
Cal()
{
a
= b = 0;
}
Cal(int x, int y)
{
a
= x;
b = y;
}
friend
ostream &operator<<(ostream &Write, Cal &C )
{
C.c=C.a+C.b;
Write<<"a
= "<<C.a<<" & b =" <<C.b<<" Sum = "<<C.c;
return
Write;
}
friend
istream &operator>>(istream
&Read, Cal &C )
{
Read>>C.a>>C.b;
return
Read;
}
};
int
main()
{
Cal
C1(10,20), C2;
cout
<<"\n\tEnter Two Nos. : ";
cin>>C2;
cout<<"\n\tSum
of : "<<C1 << endl;
cout
<<"\n\tSum of :" <<C2 <<
endl;
return
0;
}
#include
<iostream.h>
#include <fstream.h>
//Example of File using Operator << >>
class
FileOp
{
private:
int
roll,marks;
public:
FileOp()
{}
friend
ostream &operator<<(ostream &Write, FileOp &FP )
{
Write<<"
Roll : "<<FP.roll<<" Marks : "<<FP.marks;
return
Write;
}
friend
istream &operator>>(istream
&Read, FileOp &FP )
{
Read>>FP.roll>>FP.marks;
return
Read;
}
};
int
main()
{
fstream
f;
f.open("aaa.txt",ios::out);
FileOp
FP1,FP2;
cout<<"\n\tEnter
Roll & Marks : " << endl;
cin>>FP1;
f.write((char
*)&FP1,sizeof(FP1));
f.close();
f.open("aaa.txt",ios::in);
f.read((char
*)&FP2,sizeof(FP2));
cout<<"Data
:" << FP2 << endl;
return
0;
}
No comments:
Post a Comment