Monday, 6 April 2015

Overloading Stream Operators using Friend function

The class istream uses the predefined stream cin that can be used to read data from the standard input device. The extraction operator >> is used for performing input operations in the iostream library. The insertion operator << is used for performing output operations in the iostream library.

Sample Program

#include <iostream.h>
class info
{
private:
int rno;
char *name;
float tot;
public:
friend istream & operator>>(istream &in, info & obj)
{
in>>obj.rno;
in>>obj.name;
in>>obj.tot;
}
friend ostream & operator<<(ostream &out, info &obj);
};
ostream & operator<<(ostream &out, info & obj)
{
out<<obj.rno;
out<<obj.name;
out<<obj.tot;
}
void main()
{
info A;
cout<<”Enter the Object Contents”;
cin>>A; // similar to cin.operator>>(A)
cout<<”Given Values are”;
cout<<A; // similar to cout.operator<<(A)
}

No comments:

Post a Comment