Monday, 14 April 2014

Write A Cpp Program To Implement The Operator Overloading With Friend Function


Write A C++ Program To Implement The Operator Overloading With Friend Function

Ex:  OPERAROR OVERLOADING, FRIEND FUNCTION.

Aim:To write a c ++ program to implement the operator overloading with friend function

Algorithm:
Step 1: Start the program.
Step 2: Create a class complex and declare real and imaginary part value and get the value.
Step 3: Declare the friend function.
Step 4: Declare the operator function for various task.
Step 5: Declare the main function and collect the all data and display it.
Step 6: Stop the program.

Program:

#include
#include
class complex
{
private:
float real;
float img;
public:
complex()
{
}
complex(int realpart)
{
real=realpart;
}
void realpart()
{
cout<<"realpart:";
cin>>real;
cout<<"imaginarypart:";
cin>>img;
}
oid outdata()
{
cout<<"("<
cout<<"+i"<
}

friend complex operator+(complex c1,complex c2);
friend complex operator-(complex c1,complex c2);
friend complex operator/(complex c1,complex c2);
friend complex operator*(complex c1,complex c2);
};
complex operator+(complex c1,complex c2)
{
complex c;
c.real=c1.real+c2.real;
c.img=c1.img+c2.img;
return(c);
}
complex operator-(complex c1,complex c2)
{
complex temp;
temp.real=c1.real-c2.real;
temp.img=c1.img-c2.img;
return(temp);
}
complex operator/(complex c1,complex c2)
{
complex temp;
float qt;
qt=(c2.real*c2.real+c2.img*c2.img);
temp.real=(c1.real*c2.real+c2.img*c2.img)/qt;
temp.img=(c1.img*c2.real-c1.real*c2.img)/qt;
return(temp);
}
complex operator*(complex c1,complex c2)
{
complex temp;
temp.real=(c1.real*c2.real)-(c1.img*c2.img);
temp.img=(c1.real*c2.img)-(c1.img*c2.real);
return(temp);
}
void main()
{
clrscr();
complex c1,c2,c3;
c1.realpart();
c2.realpart();
c3=c1+c2;
cout<<"addition:";
c3.outdata();
c3=c1-c2;
cout<
c3.outdata();
c3=c1*c2;
cout<
c3.outdata();
c3=c1/c2;
cout<
c3.outdata();
getch();
}

Output:


Real Part: 1
Imaginary Part: 2
Real Part: 1
Imaginary Part: 2

Addition: (2+i0)
Subtraction: (0+i0)
Multiplication: (-3+i0)
Division: (1+i0)

Result:

Thus the implementation of c ++ program for the operator overloading with friend function is executed and the output has been verified.



0 comments:

Post a comment