Write a program to multiply two complex number and stored in third one by the concept of operator overloading using member function.
#include <iostream>
using namespace std;
class ComplexNumber
{
private:
double realPart;
double imaginaryPart;
public:
ComplexNumber()
{
realPart = 0;
imaginaryPart = 0;
}
ComplexNumber(double realPart, double imaginaryPart)
{
this->realPart = realPart;
this->imaginaryPart = imaginaryPart;
}
friend ComplexNumber operator *(ComplexNumber firstNumber, ComplexNumber secondNumber)
{
double realPart = firstNumber.realPart * secondNumber.realPart;
double imaginaryPart = firstNumber.imaginaryPart * secondNumber.imaginaryPart;
return ComplexNumber(realPart, imaginaryPart);
}
void print()
{
if(realPart == 0 && imaginaryPart == 0)
cout << realPart;
else if(realPart == 0)
cout << imaginaryPart << "i";
else
{
cout << realPart;
if(imaginaryPart > 0)
cout << "+";
cout << imaginaryPart << "i";
}
}
};
int main()
{
ComplexNumber firstNumber(2,3);
ComplexNumber secondNumber(4,-6);
cout << "First complex number: ";
firstNumber.print();
cout << endl;
cout << "Second complex number: ";
secondNumber.print();
cout << endl << endl;
ComplexNumber resultOfMultiplication = firstNumber * secondNumber;
cout << "Result of multiplication: ";
resultOfMultiplication.print();
cout << endl << endl;
return 0;
}
Comments
Leave a comment