Develop c++ program with a class complex containing data members real and imaginary .Overload'+' operator and '-: operator to perform complex number addition and subtraction
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imaginary;
public:
Complex(): real(0), imaginary(0){ }
void input(){
cout << "Enter real part: ";
cin >> real;
cout << "Enter imaginary part: ";
cin >> imaginary;
}
Complex operator + (Complex c2)
{
Complex result;
result.real = real + c2.real;
result.imaginary = imaginary + c2.imaginary;
return result;
}
Complex operator - (Complex c2)
{
Complex result;
result.real = real - c2.real;
result.imaginary = imaginary - c2.imaginary;
return result;
}
void dipslay()
{
if(imaginary < 0)
cout << real << imaginary << "i";
else
cout << real << "+" << imaginary << "i";
}
};
int main()
{
Complex Complex1, Complex2, result;
cout<<"Enter first complex number:\n";
Complex1.input();
cout<<"Enter second complex number:\n";
Complex2.input();
result = Complex1 + Complex2;
cout<<"\nSum: ";
result.dipslay();
result = Complex1 - Complex2;
cout<<"\nDifference: ";
result.dipslay();
cout<<"\n\n";
system("pause");
return 0;
}
Comments
Leave a comment