Please help write this program in c++ Define a complex class with private and pu
ID: 3795954 • Letter: P
Question
Please help write this program in c++
Define a complex class with private and public members using operator-overloading techniques to add, subtract, multiply and divide complex numbers. The over-loaded operators are: +, -, *, and/You need to write these prototypes for over-loaded operator functions: operator+(complex x); operator-(complex x); operator*(complex x); operator/(complex x); You also need to define constructors, input and output data functions. Your program should perform the following operations on complex objects as shown below: complex n1, n2, n3; n3 = n1 + n2; n3 = n1 - n2; n3 = n1 * n2; n3 = n1/n2;Explanation / Answer
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex(): real(0), imag(0){ }
void input()
{
cout << "Enter real and imaginary parts respectively: ";
cin >> real;
cin >> imag;
}
// Operator overloading
Complex operator - (Complex c2)
{
Complex temp;
temp.real = real - c2.real;
temp.imag = imag - c2.imag;
return temp;
}
Complex operator + (Complex c2)
{
Complex temp;
temp.real = real + c2.real;
temp.imag = imag + c2.imag;
return temp;
}
Complex operator * (Complex c2)
{
Complex temp;
temp.real = real * c2.real;
temp.imag = imag * c2.imag;
return temp;
}
Complex operator / (Complex c2)
{
Complex temp;
temp.real = real / c2.real;
temp.imag = imag / c2.imag;
return temp;
}
void output()
{
if(imag < 0)
cout << "Output Complex number: "<< real << imag << "i";
else
cout << "Output Complex number: " << real << "+" << imag << "i";
}
};
int main()
{
Complex c1, c2, result;
int choice;
char i;
cout << "1.Substraction() 2.Addition() 3.Multiplication() 4.Division ";
cout << "Enter your choice: ";
cin >> choice;
do{
switch(choice){
case 1:
cout<<"Enter first complex number: ";
c1.input();
cout<<"Enter second complex number: ";
c2.input();
result = c1 - c2;
result.output();
break;
case 2:
cout<<"Enter first complex number: ";
c1.input();
cout<<"Enter second complex number: ";
c2.input();
result = c1 + c2;
result.output();
break;
case 3:
cout<<"Enter first complex number: ";
c1.input();
cout<<"Enter second complex number: ";
c2.input();
result = c1 * c2;
result.output();
break;
case 4:
cout<<"Enter first complex number: ";
c1.input();
cout<<"Enter second complex number: ";
c2.input();
result = c1 / c2;
result.output();
break;
default: cout << "Choose RIGHT option ";
}
cout << " Do you want to proceed [Y/N]: ";
cin >> i;
}while(i == 'Y' || i == 'y');
// In case of operator overloading of binary operators in C++ programming,
// the object on right hand side of operator is always assumed as argument by compiler.
return 0;
}