64 642
Assignments Done
99,2%
Successfully Done
In September 2018

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).
Expert's answer
//complex class

#include <iostream>
using namespace std;

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

//overloadingof operators of +,- and << for
//adding,subtracting and output data, respectively
//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){
}

//adding
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!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions