4 Stream operators are “>>” and “<<”.
4 To design manipulator objects, stream operators must be overloaded.
4 The syntax for input manipulator is:
friend istream& operator >>(istream&, class&);
4 The syntax for output manipulator is:
friend ostream& operator <<(ostream&, class&);
4 Implementing functions of manipulators do not include “friend” keyword.
Example:
class complex
{
private:
double r,i;
public:
complex() { }
complex(double rr,double ii) { r=rr; i=ii;}
friend ostream& operator <<(ostream&,complex&);
friend istream& operator >>(istream&,complex&);
};
ostream& operator <<(ostream& os,complex& k)
{
os<<endl<<k.r<<" "<<k.i<<"i";
return os;
}
istream& operator >>(istream& is,complex& k)
{
cout<<endl<<"Enter Real,Imaginary:\n";
is>>k.r>>k.i;
return is;
}
main()
{
complex c1,c2;
cin>>c1>>c2;
cout<<c1<<c2;
}
Explanation:
The above program uses both input and output manipulators. To read objects “c1” and “c2”, we can simply write “cin>>c1>>c2”. With this, the input manipulator is called and data is read for the data members. Similarly, to print “c1” and “c2”, operator “<<” can be used.
0 comments:
Post a Comment