1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <iostream>
using namespace std;
class Complex {
private:
double re, img; // real and imaginary part
public:
Complex(double real, double imaginary): re{real}, img{imaginary}{}
Complex(double real): re{real}, img{0}{}
Complex(): re{0}, img{0}{}
double real() const {return this->re;}
void real(double real) {this->re = real;}
double imaginary() const {return this->img;}
void imaginary(double imaginary) {this->img = imaginary;}
Complex & operator+=(const Complex & z) {this->re += z.re; this->img += z.img; return *this;}
Complex & operator-=(Complex & z) {this->re -= z.re; this->img -= z.img; return *this;}
Complex & operator*=(Complex & z) {this->re *= z.re; this->img *= z.img; return *this;}
Complex & operator/=(Complex & z) {this->re /= z.re; this->img /= z.img; return *this;}
friend ostream & operator<<(ostream & o, Complex & c);
};
Complex & operator+(Complex a, const Complex & b) {return a+=b;}
Complex operator-(Complex a, Complex b) {return a-=b;}
Complex operator-(Complex a) {return {-a.real(), -a.imaginary()};}
Complex operator*(Complex a, Complex b) {return a+=b;}
Complex operator/(Complex a, Complex b) {return a/=b;}
bool operator==(Complex a, Complex b) {
return a.real() == b.real() && a.imaginary() == b.imaginary();
}
bool operator!=(Complex a, Complex b) {
return !(a==b);
}
ostream & operator<<(ostream & o, Complex & c) {
o << "(" << c.real() << "," << c.imaginary() << ")";
return o;
}
/*
*
*/
int main(int argc, char** argv) {
Complex a(10, 3);
Complex b(4, 5);
cout << a << "\n";
cout << b << "\n";
b += a;
cout << a << "\n";
cout << b << "\n";
// This works but I don't know why?
cout << "here's the plus operator at work" << "\n";
Complex c = a + b;
cout << a << "\n";
cout << b << "\n";
cout << c << "\n";
return 0;
}
|