#include <iostream>
using namespace std;
class ComplexNumber {
public:
ComplexNumber(double re = 0.0, double im = 0.0) : real(re), imag(im) { }
double getReal();
double getImag();
void setReal(double);
void setImag(double);
friend ComplexNumber operator+ (const ComplexNumber &a, const ComplexNumber &b);
friend ComplexNumber operator- (const ComplexNumber &a, const ComplexNumber &b);
friend ComplexNumber operator* (const ComplexNumber &a, const ComplexNumber &b);
friend ComplexNumber operator/ (const ComplexNumber &a, const ComplexNumber &b);
friend ostream& operator<<(ostream &out, const ComplexNumber &c);
private:
double real;
double imag;
};
double ComplexNumber::getReal() {
return real;
}
double ComplexNumber::getImag() {
return imag;
}
void ComplexNumber::setReal(double re) {
real=re;
}
void ComplexNumber::setImag(double im) {
imag=im;
}
ComplexNumber operator+ (const ComplexNumber &a, const ComplexNumber &b) {
ComplexNumber result;
result.real = a.real + b.real;
result.imag = a.imag + b.imag;
return result;
}
ComplexNumber operator- (const ComplexNumber &a, const ComplexNumber &b) {
ComplexNumber result;
result.real = a.real - b.real;
result.imag = a.imag - b.imag;
return result;
}
ComplexNumber operator* (const ComplexNumber &a, const ComplexNumber &b) {
ComplexNumber result;
result.real = (a.real * b.real - a.imag * b.imag);
result.imag = (a.real * b.imag + a.imag * b.real);
return result;
}
ComplexNumber operator/ (const ComplexNumber &a, const ComplexNumber &b) {
ComplexNumber result;
result.real = (a.real * b.real + a.imag * b.imag) / (b.real * b.real + b.imag * b.imag);
result.imag = (a.imag * b.real - a.real * b.imag) / (b.real * b.real + b.imag * b.imag);
return result;
}
ostream& operator<< (ostream &out, const ComplexNumber &c) {
out << c.real << "+" << c.imag << "i";
return out;
}
int main () {
ComplexNumber x(1, 2), y, z;
ComplexNumber sum, difference, product, quotient;
y = ComplexNumber(2, 4);
z = ComplexNumber(3, 0);
cout << "x is: " << x << endl;
cout << "y is: " << y << endl;
cout << "z is: " << z << endl;
cout << "x real="<<x.getReal()<<" x imag="<<x.getImag()<<endl;
sum = x + y;
difference = x - y;
product = x * y;
quotient = sum / z;
cout << "The sum (x + y) is: " << sum << endl;
cout << "The difference (x - y) is: " << difference<< endl;
cout << "The product (x * y) is: " << product << endl;
cout << "The quotient (sum / z) is: " << quotient << endl;
return 0;
}