98 943
Assignments Done
98.8%
Successfully Done
In May 2021

# Answer to Question #28610 in C++ for Urwa zainab

Question #28610
Create a class complex for performing arithmetic with complex numbers. Write a program to test your class. Complex numbers have the form real and imaginary part. Use double variable to represent private data of class. Add and Subtract 2 complex numbers. Print complex numbers in form (a,b).
1
2013-04-16T08:54:00-0400
//complex class

#include <iostream>
using namespace std;

//declaration
class Complex {
public:
Complex(doubleRe = 0, double Im = 0);

//friendclass is needed for access private members of class
friendComplex operator+ (const Complex& c1, const Complex& c2);
friendComplex operator- (const Complex& c1, const Complex& c2);

friendostream& operator<< (ostream& out, const Complex& c);

private:
doublem_Re;
doublem_Im;
};

//implementation
//consturctor
Complex::Complex (double Re, double Im) :
m_Re(Re),
m_Im(Im){
}

Complex operator+ (const Complex& c1, constComplex& c2) {
returnComplex(c1.m_Re + c2.m_Re, c1.m_Im + c2.m_Im); }

//substracting
Complex operator- (const Complex& c1, constComplex& c2) {
returnComplex(c1.m_Re - c2.m_Re, c1.m_Im - c2.m_Im); }

//outputing
//you can use this with simply ostream streams for output//i.e cout << Complex(2.545, 2.313); //or in file in the same way //you
can also make another operator to output in usual way: Re + i*Im; ostream&
operator<< (ostream& out, const Complex& c) {
out<< "(" << c.m_Re << "," << c.m_Im
<< ")";
returnout;
}

//some testing
int main() {
Complexc1 ; //will bee 0 +i0
Complexc2 (2.56, 1.23);
Complexc3 (5.56, 0.23);
Complexc4 (-23.56, -3.451);

cout<< c1 + c2 << " " << c1 - c2 << endl;
cout<< c3 + c2 << " " << c3 - c1 << endl;
cout<< c4 + c3 << " " << c4 - c3 << endl;

cout<< c1 << " " << c2 << " "
<< c3 << " " << c4 << " "
<< endl;
//" "symbol is tabulation
//endl- new line
return0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!