In: Computer Science
2. A complex number can be expressed as a + bi where a and b are real numbers and i is the imaginary unit. The multiplication of two complex numbers is defined as follows:
(a+bi)(c+di) = (ac-bd) + (bc+ad)i
Define a class which represents a complex number. The only member functions you have to define and implement are those which overload the * and *= symbols.
In C++ please, thank you
Given below is the code for question. I have written a main() to
show that the implementation is correct
Please do rate the answer if it helped. thank you.
#include <iostream>
using namespace std;
class Complex{
private:
double a, b;
public:
Complex(double a1 =0 , double b1 = 0){
a = a1;
b = b1;
}
Complex operator *( const Complex &c){
double re = a * c.a - b *c.b;
double im = b * c.a + a *
c.b;
return Complex(re, im);
}
Complex & operator *= (const Complex
&c){
*this = (*this) * c;
return *this;
}
void print(){
cout << a << " + "
<< b << " i" << endl;
}
};
int main(){
Complex c1(1, 2), c2(3, 4);
Complex c3 = c1 * c2;
cout << "c1 is ";
c1.print();
cout << "c2 is ";
c2.print();
cout << "c3 is ";
c3.print();
cout << "now c3 *= c2" << endl;
c3 *= c2;
cout << "c2 is ";
c2.print();
cout << "c3 is ";
c3.print();
}
output
-----
c1 is 1 + 2 i
c2 is 3 + 4 i
c3 is -5 + 10 i
now c3 *= c2
c2 is 3 + 4 i
c3 is -55 + 10 i