Stream operator overloading
Aim:To write a C++ program to add two values using stream operator overloading.
Algorithm:
Step 1: Declare the class as add.
Step 2: Declare the data members as a, b.
Step 3: Declare the member functions as
friend istream & operator >>(istream &in,add &d)
friend ostream & operator <<(ostream &out,add &d)
Step 4: In the main, create the object for the add class.
Step 5: Get the input values by overloading “<<” operator.
Step 6: Add the values and display the values using “>>”operator.
Program:
#include<iostream.h>
#include<conio.h>
class add
{
int a,b;
public:
friend istream &operator>>(istream &in,add &d);
friend ostream &operator<<(ostream &out,add &d);
};
istream &operator>>(istream &in,add &d)
{
in>>d.a;
in>>d.b;
return in;
}
ostream &operator<<(ostream &out,add &d)
{
out<<d.a+d.b;
return out;
}
void main()
{
add d;
clrscr();
cout<<"ENTER THE VALUES FOR a AND b:";
cin>>d;
cout<<"\nTHE SUM IS:";
cout<<d;
getch();
}
Output:
ENTER THE VALUES FOR a AND b:5 7
THE SUM IS:12
0 comments:
Post a Comment