Overloading << and >>
#include <iostream>
using namespace std;
#include "stdio.h"
class Complex
{
int real;
int img;
public:
Complex()
{
//cout<<"Inside the constructor..."<<endl;
real =10;
img = 50;
}
~Complex()
{
//cout<<"Inside the destructor..."<<endl;
}
friend ostream& operator << (ostream& s, Complex& c); //This is needed as the fun uses private data os Complex class
friend istream& operator >> (istream& s, Complex& c);
};
ostream& operator << (ostream& s, Complex& c)
{
printf("Inside overloaded << operator\n");
s<<c.real<<"+i"<<c.img<<endl;
return s;
}
istream& operator >> (istream& s, Complex& c)
{
printf("Inside overloaded >> operator\n");
printf("Enter real and img number: \n");
s>>c.real>>c.img;
return s;
}
int main()
{
Complex c;
cout<<c; //This will call the overloaded << operator defined in this program
cout<<"Kalyan"<<endl; //This will not call our defined << operator
cin>>c;//This will call our defined >> operator
cout<<c; //This will call our defined << operator
return 0;
}
Output:
Inside overloaded << operator
10+i50
Kalyan
Inside overloaded >> operator
Enter real and img number:
Inside overloaded << operator
10+i50
Copyright © Open Sky Technology |