CSIT Object Oriented Programming with C++(Insertion and Extraction Operator Overloading ) Part VI
I am assuming that, You have already studied previous parts of Operator Overloading Series. So in this post, I am going to teach you How to Overload Insertion and Extraction operator.
Here, I will overload '<<' and '>>' operator to input and output distance class data.
So, let's get started,
#include<iostream>
using namespace std;
class Distance{
int feet,inch;
public:
Distance(){
feet=0;inch=0;
}
Distance(int f,int i){
feet=f;inch=i;
}
friend ostream &operator <<(ostream &output , const Distance &d)
{
output<<"Feet: "<<d.feet<<" Inch: "<<d.inch<<endl;
return output;
}
friend istream &operator >>(istream &input, Distance& d)
{
input>>d.feet>>d.inch;
return input;
}
};
int main()
{
Distance d1(4,8), d2;
cin>>d2;
cout<<d1<<endl;
cout<<d2;
return 0;
}
In this way we can overload insertion and extraction operator.
Comments
Post a Comment