In: Computer Science
Must be in C++ (beginners coding class)
8.
a. Rewrite the definition of the class complexType so that the arith-metic and relational operators are overloaded as nonmember functions.
b. Write the definitions of the member functions of the class complexType as designed in part a.
c. Write a test program that tests various operations on the class complexType as designed in parts a and b. Format your answer with two decimal places.
(additional info/problem ) does not need to be answered only number 8 needs to be answered
a. Extend the definition of the class complexType so that it performs the subtraction and division operations. Overload the operators subtrac-tion and division for this class as member functions.
If (a, b) and (c, d ) are complex numbers:
(a, b)-(c, d )=(a - c, b - d ).
If (c, d ) is nonzero:
(a, b)/(c, d)=((ac + bd )/(c2+ d2), (-ad + bc)/(c2+ d2)).
b. Write the definitions of the functions to overload the operators - and / asdefined in part a.
c. Write a test program that tests various operations on the classcomplexType. Format your answer with two decimal places.
#include<iostream>
#include<iomanip>
using namespace std;
class complexType{
private:
double real,imag;
public:
complexType(){
real = 0;
imag = 0;
}
complexType(double r , double
i){
real = r;
imag = i;
}
void setReal(double r){
real = r;
}
void setImag(double i){
imag = i;
}
double getReal(){
return
real;
}
double getImag(){
return
imag;
}
complexType& operator+(const
complexType& other){
double r = real
+ other.real;
double i = imag
+ other.imag;
return *(new
complexType(r , i));
}
complexType& operator-(const
complexType& other){
double r = real
- other.real;
double i = imag
- other.imag;
return *(new
complexType(r , i));
}
complexType& operator*(const
complexType& other){
double r = real
* other.real - imag*other.imag;
double i =
imag*other.real + real*other.imag;
return *(new
complexType(r , i));
}
complexType& operator/(const
complexType& other){
double val =
(other.real* other.real + other.imag*other.imag);
double r = (real
* other.real + imag*other.imag)/val;
double i =
(imag*other.real - real*other.imag)/val;
return *(new
complexType(r , i));
}
friend ostream& operator
<< (ostream& out , const complexType& other){
out<<setprecision(2)<<fixed;
out<<"("<<other.real<<",
"<<other.imag<<")";
return
out;
}
friend istream& operator
>> (istream& in , complexType& other){
char ch;
in>>ch>>other.real>>ch>>other.imag>>ch;
return in;
}
};
int main(){
complexType c1(2,3);
complexType c2(4,5),c3;
c3 = c1 + c2;
cout<<"c1 + c2 = "<<c3<<endl;
c3 = c1 - c2;
cout<<"c1 - c2 = "<<c3<<endl;
c3 = c1 * c2;
cout<<"c1 * c2 = "<<c3<<endl;
c3 = c1 / c2;
cout<<"c1 / c2 = "<<c3<<endl;
return 0;
}