-For the COMPLEX class listed on the next page write code to:
a) overload the addition operator for addition between two COMPLEX values.
b) Create a constructor that uses a single parameter to initialize the real member of a COMPLEX and sets the imaginary portion to 0.
c) Write the code to produce the insertion operator.
#include <iostream>
using namespace std;
class COMPLEX{
double Re;
double Im;
public:
COMPLEX(double r, double im);
COMPLEX(const COMPLEX &c)
{
Re = c.Re;
Im = c.Im;
}
COMPLEX( )
{
Re = Im = 0;
}
~COMPLEX( )
{
}
COMPLEX operator*(const COMPLEX & b) const;
COMPLEX operator*(const double &x) const;
friend COMPLEX operator*(const double &x, const
COMPLEX &c);
COMPLEX operator-(const COMPLEX &b) const;
COMPLEX operator-( ) const;
friend ostream& operator<<(ostream&,
const COMPLEX &);
};
Here is the completed code for each question. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
//a) method declaration for overloading addition operator (should be placed inside
//the COMPLEX class)
COMPLEX operator+(const COMPLEX &b) const;
//a) method definition for overloading addition operator, should be placed outside class
COMPLEX COMPLEX::operator+(const COMPLEX &b) const{
//creating a COMPLEX object after adding corresponding real and imaginary
//values of this number and b
COMPLEX result=COMPLEX(Re+b.Re , Im+b.Im);
return result; //returning it
}
//end of question (a)
//b) declaration for constructor taking value for real part only
//(should be placed inside the COMPLEX class)
COMPLEX(double r);
//b) constructor definition, should be placed outside class
COMPLEX::COMPLEX(double r){
Re=r;
Im=0; //setting imaginary part to 0
}
//end of question (b)
//c) overloading << operator (insertion). this only needs definition as declaration
//is already done inside COMPLEX class. this should be placed outside class
ostream& operator<<(ostream& out, const COMPLEX &c){
//printing the complex number in format a+bi or a-bi
//checking if imaginary part is positive
if(c.Im>=0){
//printing in format a+bi
out<<c.Re<<"+"<<c.Im<<"i";
}else{
//printing in format a -bi
out<<c.Re<<c.Im<<"i";
}
return out;
}
//end of question (c)
Get Answers For Free
Most questions answered within 1 hours.