Write the definition for a class called complex that has floating point data mem
ID: 3800031 • Letter: W
Question
Write the definition for a class called complex that has floating point data members for storing real and imaginary parts. The class has the following member function: void disp() to display complex number object Define a constructor to set the values of the objects. Write main function to create five complex number objects. Set the value in two objects using constructor & Use Operator overloading to find sum, difference and product of the complex numbers and return in the 3^rd, 4^th & 5^th object respectively. Display all complex numbers.Explanation / Answer
Here is the solution:
#include <iostream>
using namespace std;
#include<string.h>
#include<stdio.h>
class complex
{
float i,r;
public:
complex(){}
complex( float real, float imag )
{
r=real;
i=imag;
}
void disp()
{
cout<<r<<"+"<<i<<"i"<<endl;
}
complex operator+(complex a2)
{
complex a;
a.r=r+a2.r;
a.i=i+a2.i;
return a;
}
complex operator-(complex a2)
{
complex a;
a.r=r-a2.r;
a.i=i-a2.i;
return a;
}
complex operator*(complex a2)
{
complex a;
a.r=(r*a2.r)-(i*a2.i);
a.i=(r*a2.i)+(i*a2.r);
return a;
}
};
int main()
{
complex c1=complex(10.05,6.00);
c1.disp();
complex c2=complex(10.00,9.00);
c2.disp();
complex c3,c4,c5;
c3=c1+c2;
c3.disp();
c4=c1-c2;
c4.disp();
c5=c1*c2;
c5.disp();
}
Output:
10.05+6i
10+9i
20.05+15i
0.05+-3i
46.5+150.45i
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.