#include <iostream>
#include <cmath>
using namespace std;
class Complex
{
public:
Complex(double a, double b = 0.0):real(a), imag(b) {}
Complex operator+ (const Complex c)
{
double r = real + c.real;
double v = imag + c.imag;
return Complex(r, v);
}
Complex operator++()
{
real++;
return *this;
}
Complex operator++(int)
{
Complex old = *this;
++(*this);
return old;
}
friend Complex operator-(const Complex c1, const Complex c2);
friend Complex operator--(Complex &c);
friend Complex operator--(Complex &c, int);
friend ostream &operator<<(ostream &out, const Complex c);
void print()
{
if (fabs(imag - 0.0) < 10e-6)
cout << real << endl;
else if (imag > 0)
cout << real << "+" << imag << "i" << endl;
else
cout << real << imag << "i" << endl;
}
private:
double real;
double imag;
};
Complex operator-(const Complex c1, const Complex c2)
{
double r = c1.real - c2.real;
double v = c1.imag - c2.imag;
return Complex(r, v);
}
Complex operator--(Complex &c)
{
c.real--;
return c;
}
Complex operator--(Complex &c, int)
{
Complex old = c;
c.real--;
return old;
}
ostream &operator<<(ostream &out, const Complex c)
{
if (fabs(c.imag - 0.0) < 10e-6)
cout << c.real;
else if (c.imag > 0)
cout << c.real << "+" << c.imag << "i";
else
cout << c.real << c.imag << "i";
}
int main(void)
{
Complex c1(0, -1.1);
Complex c2(2.6);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
(c3--).print();
cout << --c4 << endl;
return 0;
}
需注意的点:
- 对于
+
、-
、++
、--
,它们既可以重载为类的成员函数,也可以重载为非成员函数 - 对于
++
、--
而言,它们又分为前置和后置两种情况,重载为前置时函数是不带形参的,但重载为后置时需要带一个 int 形参;问我为什么,那就是 老鳖的屁股—规定;且对于函数参数表中未使用到的参数,C++ 允许不给出参数名 <<
只能重载为非成员函数