//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;
}
Comments
Leave a comment