Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Define a class for Complex Numbers. Represent Complex Number as 2 values of type

ID: 3722149 • Letter: D

Question

Define a class for Complex Numbers. Represent Complex Number as 2 values of type double real and imag. Call the class Complex.

Include a constructor with 2 arguments R and I, this constructor should set the values of real and imag to the passed arguments.

Overload the following operators: +, -, *, >>, <<.

<< should print the complex number object in the following format "a+bi"

>> should read the complex number object"

+ should add 2 complex numbers objects and return an complex number object

- should subtract 2 complex numbers objects and return an complex number object

* should multiply 2 complex numbers objects and return an complex number object

Also write a test program to test your class.

(done in c++)

Explanation / Answer

#include<iostream>  
using namespace std;
class complex  
{  
double i,r;  
public:  
complex(double a,double b)  
{  
r=a;
i=b;
}  
complex()
{
r=0;i=0;
}
void display()  
{  
cout<<" = "<<r<<"+"<<i<<"i";  
}  
complex operator+(complex a2)  
{  
complex temp;  
temp.r=r+a2.r;  
temp.i=i+a2.i;  
return temp;  
}  
complex operator-(complex a2)  
{  
complex temp;  
temp.r=r-a2.r;  
temp.i=i-a2.i;  
return temp;  
}  
complex operator*(complex a2)  
{  
complex temp;  
temp.r=(r*a2.r)-(i*a2.i);  
temp.i=(r*a2.i)+(i*a2.r);  
return temp;  
}  
  
};  
int main()  
{  

complex a(1.0,2.0),b(2.0,3.0),c;

c=a+b;
a.display();
b.display();
cout<<" .Addition "<<endl;
c.display();
cout<<" .Substraction "<<endl;

c=a-b;
c.display();
cout<<" .Mulitplication "<<endl;

c=a*b;
c.display();

}

Output:-


= 1+2i
= 2+3i
.Addition

= 3+5i
.Substraction

= -1+-1i
.Mulitplication

= -4+7i

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote