Construct the class Complex that has floating point data members for storing real and imaginary parts and perform complex number subtraction using operator Overloading.
he class Complex has the following member functions:
Complex() - Null constructor invokes when an object is created
Complex(float, float) - Parameterized constructor to set the specified value of real and imaginary parts in object
Operator()- To subtract an object from another object
print() - Function to display complex number object
Test Case: 1
INPUT:
R1:15
I1: 2
R2: 5
I2: 10
OUTPUT:
A =15 + i2
B = 5 + i10
C = 10 + i(-8)
#include <iostream>
using namespace std;
class Complex{
float real, imaginary;
public:
Complex(){}
Complex(float a, float b): real(a), imaginary(b){}
void Print(){
cout<<real;
if(imaginary != 0) cout<<" + "<<"i";
if(imaginary < 0) cout<<"("<<imaginary<<")";
else cout<<imaginary;
}
Complex operator-(const Complex &other){
return Complex(this->real - other.real, this->imaginary - other.imaginary);
}
};
int main(){
cout<<"INPUT:\n";
cout<<"R1:";
float R1; cin>>R1;
cout<<"I1:";
float I1; cin>>I1;
cout<<"R2:";
float R2; cin>>R2;
cout<<"I2:";
float I2; cin>>I2;
Complex A(R1, I1), B(R2, I2), C = A - B;
cout<<"\nOutput\n";
cout<<"A = "; A.Print(); cout<<endl;
cout<<"B = "; B.Print(); cout<<endl;
cout<<"C = "; C.Print(); cout<<endl;
return 0;
}
Comments
Leave a comment