本文将实现复数类的各种运算符重载。
Complex.h:
#include <iostream>
using namespace std;
class Complex {
friend ostream &operator<< (ostream &os, const Complex a);
public:
Complex operator+(const Complex &add);
Complex operator-(const Complex &sub);
Complex operator*(const Complex &mul);
Complex operator/(const Complex &chu);
Complex& operator+=(const Complex &add);
Complex& operator-=(const Complex &sub);
Complex& operator*=(const Complex &mul);
Complex& operator/=(const Complex &chu);
bool operator==(const Complex &l);
bool operator!=(const Complex &l);
Complex();
Complex(double, double);
void SetReal(double re);
void SetImag(double im);
private:
double real;
double imag;
};
Complex.cpp:
ostream &operator<< (ostream &os, const Complex a);
Complex::Complex() {
real = 0;
imag = 0;
}
Complex::Complex(double x, double y) {
real = x;
imag = y;
}
void Complex::SetReal(double re) {real = re;}
void Complex::SetImag(double im) {imag = im;}
ostream &operator<< (ostream &os, const Complex a) {
os << a.real << "+" << a.imag << "i";
return os;
}
Complex Complex::operator+(const Complex &add) {
Complex result;
result.real = real + add.real;
result.imag = imag + add.imag;
return result;
}
Complex Complex::operator-(const Complex &sub) {
Complex result;
result.real = real - sub.real;
result.imag = imag - sub.imag;
return result;
}
Complex Complex::operator*(const Complex &mul) {
Complex result;
result.real = real * mul.real - imag * mul.imag;
result.imag = real * mul.imag + imag * mul.real;
return result;
}
Complex Complex::operator/(const Complex &chu) {
Complex result, temp;
temp.real = chu.real, temp.imag = -chu.imag;
result.real = real * temp.real - imag * temp.imag;
result.imag = real * temp.imag + imag * temp.real;
double N;
N = chu.real * chu.real + chu.imag * chu.imag;
result.real /= N;
result.imag /= N;
return result;
}
bool Complex::operator==(const Complex &l) {return real == l.real && imag == l.imag;}
bool Complex::operator!=(const Complex &l) {return !(real == l.real && imag == l.imag);}
Complex& Complex::operator+=(const Complex &add) {
real += add.real;
imag += add.imag;
return *this;
}
Complex& Complex::operator-=(const Complex &sub) {
real -= sub.real;
imag -= sub.imag;
return *this;
}
Complex& Complex::operator*=(const Complex &mul) {
*this = *this * mul;
return *this;
}
Complex& Complex::operator/=(const Complex &chu) {
*this = *this / chu;
return *this;
}
client.cpp:
int main() {
double x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
Complex a(x1, y1), b(x2, y2);
Complex c = a;
double c1, c2;
cin >> c1 >> c2;
c.SetReal(c1);
c.SetImag(c2);
cout << c << endl;
cout << a << endl;
c = b;
cout << c << endl;
cout << (a + b) << endl;
cout << (a - b) << endl;
cout << (a * b) << endl;
cout << (a / b) << endl;
a += b;
cout << a << endl;
a -= b;
cout << a << endl;
a *= b;
cout << a << endl;
a /= b;
cout << a << endl;
cout << (a == a) << endl;
cout << (a != a) << endl;
return 0;
}