跳到内容

运算符重载基础 ​

为什么重载运算符 ​

上一章我们给类写了 show()、largerThan() 这样的方法。如果两个对象想相加,你得写 c = a.add(b),读起来不如 c = a + b 自然。运算符重载让你能给类的对象重新定义 +、-、* 等运算符的含义,使自定义类型用起来像内置类型一样直观。

这是 OOP "抽象"的延续:int 的 + 是求和,std::string 的 + 是拼接,你的 Vector 的 + 可以是向量相加——同一个运算符,在不同类型上有不同但符合直觉的行为。

运算符函数的写法 ​

重载运算符就是写一个特殊名字的函数:operator 加上运算符符号。例如 operator+、operator-。它可以作为成员函数,也可以作为普通函数(非成员)。

成员函数形式:

cpp
class Duration
{
private:
    int minutes;
public:
    Duration(int m = 0) : minutes(m) {}
    // 重载 + 为成员函数
    Duration operator+(const Duration& other) const;
    int value() const { return minutes; }
};

Duration Duration::operator+(const Duration& other) const
{
    return Duration(minutes + other.minutes);
}

调用时,a + b 等价于 a.operator+(b)——左操作数就是调用对象,右操作数是参数。

cpp
#include <iostream>

int main()
{
    Duration a(30);
    Duration b(45);
    Duration c = a + b;          // 等价于 a.operator+(b)
    std::cout << c.value() << "\n";   // 75
    return 0;
}

成员函数 vs 非成员函数 ​

同一个运算符可以两种方式重载:

  • 成员函数:左操作数必须是本类对象。a + b 里 a 必须是 Duration。
  • 非成员函数(通常声明为友元):左操作数可以是别的类型。比如 2.5 * vec,左操作数是 double,只能用非成员函数。

很多二元运算符两种写法都行,选哪个看左操作数是否一定是本类对象。下一节的友元会专门讲非成员形式。

可重载的运算符与限制 ​

C++ 允许重载绝大多数运算符,常用的有算术(+ - * / %)、关系(== != < > <= >=)、下标 []、调用 ()、赋值 =、输入输出 << >> 等。

有几条硬性限制:

  • 不能创建新运算符:只能重载已有的,不能发明 operator** 之类。
  • 不能改变运算符的操作数个数:+ 是二元,重载后还是二元。
  • 不能改变优先级和结合性:* 仍比 + 先算。
  • 不能重载这几个:. .* :: ?: sizeof。
  • 重载后的运算符至少要有一个操作数是用户自定义类型——不能重新定义两个 int 相加的含义。

一元运算符的重载 ​

一元运算符如负号 -、逻辑非 ! 可以重载。作为成员函数时不带参数(操作数就是调用对象):

cpp
class Duration
{
    int minutes;
public:
    Duration(int m = 0) : minutes(m) {}
    Duration operator-() const;        // 一元负号
    int value() const { return minutes; }
};

Duration Duration::operator-() const
{
    return Duration(-minutes);
}
cpp
Duration d(30);
Duration e = -d;        // 等价于 d.operator-()
std::cout << e.value(); // -30

重载的原则 ​

重载运算符是为了让代码更清晰,而不是炫技。使用时把握几条原则:

  • 含义要符合直觉:+ 应该是某种"相加/合并",< 应该是某种"排序比较"。如果找不到自然含义,老老实实用普通方法名。
  • 不要改变 surprises:+ 不应该偷偷修改操作数——把它声明成 const 成员函数返回新对象。
  • 保持可预期:如果定义了 +,最好也定义 -=、+= 之类配套;定义了 ==,最好也定义 !=。
  • 返回类型要合适:算术运算通常返回新对象(按值),复合赋值 += 通常返回 *this 的引用,输入输出 << >> 返回流引用以支持链式。

一个完整的小例子 ​

把上面的片段组合起来:

cpp
#include <iostream>

class Duration
{
    int minutes;
public:
    Duration(int m = 0) : minutes(m) {}
    Duration operator+(const Duration& other) const;
    Duration operator-() const;
    bool operator<(const Duration& other) const;
    int value() const { return minutes; }
};

Duration Duration::operator+(const Duration& other) const
{
    return Duration(minutes + other.minutes);
}

Duration Duration::operator-() const
{
    return Duration(-minutes);
}

bool Duration::operator<(const Duration& other) const
{
    return minutes < other.minutes;
}

int main()
{
    Duration a(20), b(35);
    Duration sum = a + b;          // 55
    Duration neg = -a;             // -20
    std::cout << "sum=" << sum.value() << " neg=" << neg.value() << "\n";
    std::cout << std::boolalpha << "a < b? " << (a < b) << "\n";  // true
    return 0;
}

a + b、-a、a < b 这些表达式读起来和内置类型一模一样——这就是运算符重载的目标。

课后练习 ​

  1. 重载加法:写一个 Money 类(成员是"分"为单位的整数),重载 operator+ 把两笔钱相加。在 main 里用 m1 + m2 形式求和并打印。
  2. 一元负号:给 Money 类重载一元 operator-,返回金额取负的新对象。测试 (-m).value() 是否等于 -m.value()。
  3. 关系比较:给 Money 重载 operator< 和 operator==,写一段代码对几个 Money 对象排序(手写比较即可,不必用标准库算法)。
  4. 限制验证:尝试在代码里写一个 operator**(两个星号当新运算符),确认编译器拒绝;再尝试重载两个 int 的 +,确认也被拒绝。理解"不能造新运算符""不能改变内置类型运算"这两条限制。