#include <iostream>
using namespace std;

class Complex {
private:
  int real, imag; //复数的实部、虚部

public:
  Complex(int r = 0, int i = 0) {
    real = r;
    imag = i;
  }

  // 在两个复数对象中使用+时,该函数会被调用
  Complex operator+(Complex const &obj) {
    Complex res;
    res.real = real + obj.real;
    res.imag = imag + obj.imag;
    return res;
  }
  void print() { cout << real << " + i" << imag << endl; }
};

int main() {
  Complex c1(10, 5), c2(2, 4);
  Complex c3 = c1 + c2; // 使用示例 "+"
  c3.print(); //12 + i9
}

下面是可重载的运算符列表。

分类 运算符列表
双目算术运算符 + (加),- (减),*(乘),/ (除),% (取模)
关系运算符 == (等于),!= (不等于),< (小于),> (大于),<= (小于等于),>= (大于等于)
逻辑运算符 || (逻辑或),&& (逻辑与),! (逻辑非)
单目运算符 + (正),- (负),* (指针),& (取地址)
自增自减运算符 ++ (自增),– (自减)
位运算符 | (按位或),& (按位与),~ (按位取反),^ (按位异或),,« (左移),» (右移)
赋值运算符 =, +=, -=, *=, /= , %= , &=, |=, ^=, «=, »=
空间申请与释放 new, delete, new[] , delete[]
其他运算符 () (函数调用),-> (成员访问),, (逗号),[] (下标)