Create a class called Complex for performing arithmetic with complex numbers. Wr
ID: 666545 • Letter: C
Question
Create a class called Complex for performing arithmetic with complex numbers.
Write a program to test your class. Complex numbers have the form
realPart + imaginaryPart * i
where i is sqrt-1
Use double variables to represent the private data of the class. Provide a constructor that enables
an object of this class to be initialized when it’s declared. The constructor should contain default
values in case no initializers are provided. Provide public member functions that perform the following
tasks:
a) Adding two Complex numbers: The real parts are added together and the imaginary
parts are added together.
b) Subtracting two Complex numbers: The real part of the right operand is subtracted from
the real part of the left operand, and the imaginary part of the right operand is subtracted
from the imaginary part of the left operand.
c) Printing Complex numbers in the form (a, b), where a is the real part and b is the imaginary
part.
d) Modify the class to enable input and output of complex numbers via overloaded >> and
<< operators, respectively (you should remove the print function from the class).
e) Overload the multiplication operator to enable multiplication of two complex numbers
as in algebra.
f) Overload the == and != operators to allow comparisons of complex numbers.
Explanation / Answer
#include<iostream>
#include<iomanip>
#include "complex.h"
using namespace std;
Complex :: Complex(double real,double imag){ //constructor
this->real=real;
this->imag=imag;
}
Complex :: ~Complex(){} //destructor
Complex Complex :: operator=(const Complex &c){
Complex d(0.0,0.0);
real=c.real;
imag=c.imag;
return d;
}
Complex Complex :: operator+(const Complex c){
Complex d(0.0,0.0);
d.real=real+c.real;
d.imag=imag+c.imag;
return d;
}
Complex Complex :: operator-(const Complex c){
Complex d(0.0,0.0);
d.real=real-c.real;
d.imag=imag-c.imag;
return d;
}
Complex Complex :: operator*(const Complex c){
Complex d(0.0,0.0);
d.real=(real*c.real)-(imag*c.imag);
d.imag=(real*c.imag)+(imag*c.real);
return d;
}
Complex Complex :: operator/(const Complex c){
Complex d(0.0,0.0);
d.real=((real*c.real)+(imag*c.imag))/((c.real*c.real)+(c.imag*c.imag));
d.imag=((imag*c.real)-(real*c.imag))/((c.real*c.real)+(c.imag*c.imag));
return d;
}
Complex Complex :: operator||(const Complex c){
Complex d(0.0,0.0);
d.real=real||c.real;
d.imag=imag||c.imag;
return d;
}
void Complex :: print() const{
if(imag>=0.0){
cout<<"("<<fixed<<setprecision (2)<<real<<", j"<<fixed<<setprecision (2)<<imag<<")";
}else{
cout<<"("<<fixed<<setprecision (2)<<real<<", -j"<<fixed<<setprecision (2)<<-imag<<")";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.