Binary operator overloading, operator overloading, function operator
Write a program in C++ to implement the concept of Binary operator overloading.


Algorithm to solve the above problem:
Step 1: Start the program.
Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step 4: Using the function getvalue() to get the two numbers.
Step 5: Define the function operator +() to add two complex numbers.
Step 6: Define the function operator –()to subtract two complex numbers.
Step 7: Define the display function.
Step 8: Declare the class objects obj1,obj2 and result.
Step 9: Call the function getvalue using obj1 and obj2
Step 10: Calculate the value for the object result by calling the function operator + and operator -.
Step 11: Call the display function using obj1 and obj2 and result.
Step 12: Return the values.
Step 13: Stop the program

Implementation of the above problem in C++:
#include<iostream>
using namespace std;
class complex
{
float x;
float y;
public:
complex()
{
}
complex(float real,float imag)
{
x=real;y=imag;
}
complex operator+(complex c);
void display(void);
};
complex complex::operator+(complex c)
{
complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return(temp);
}
void complex::display(void)
{
cout<<x<<"+j"<<y<<"\n";
}
int main()
{

complex c1,c2,c3;
c1=complex(3.8,4.9);
c2=complex(3.2,6.7);
c3=c1+c2;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
cout<<"c3=";
c3.display();
return 0;
}


The output of the above program is tested on www.jdoodle.com
Output:
c1=3.8+j4.9
c2=3.2+j6.7
c3=7+j11.6


Thanks
Mukesh Rajput
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: