Write a C++ program for using operator overloading.

Algorithm:
Step 1: Start the program.
Step 2: Create a class called complex.
Step 3: Initialize the complex data members inside the constructor.
Step 4: Define the operator+ using operator overloading.
Step 5: Create an object and call the member functions.
Step 6: Print the output.
Step 7: Stop the program.





Program Code:
#include<iostream.h>
#include<conio.h>
class complex
{
float x;
float y;
public:
complex()
{
}
complex(float real,float imag)
{
x=real;
y=imag;
}
complex operator+(complex);
void display();
};
complex complex ::operator+(complex c)
{
complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return(temp);
}
void complex::display()
{
cout<<x<<"+j"<<y<<"\n";
}
void main()
{
complex c1,c2,c3;
c1=complex(2.5,3.5);
c2=complex(1.6,2.7);
c3=c1+c2;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
cout<<"c3=";
c3.display();
return 0;
}




Output:
c1=2.5+j3.5
c2=1.6+j2.7
c3=4.1+j6.2
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: