运算符重载与三向比较

C++ 的运算符重载让自定义类型可以像内置类型一样自然地使用 +、==、< 等运算符。C++20 引入的三向比较运算符 <=>(spaceship operator)更是将六个比较运算符的实现简化为一行代码。本节从基础规则讲起,最终掌握现代 C++ 中运算符重载的最佳实践。

1. 运算符重载基础

运算符重载的本质是给已有的运算符赋予新含义,使其能作用于用户自定义类型。其核心动机是:让代码读起来更自然。

// 没有运算符重载 — 晦涩难懂
Vec2 result = vec_add(vec_mul(a, 2.0), b);

// 有运算符重载 — 直观明了
Vec2 result = a * 2.0 + b;

基本规则

  • 不能创造新运算符 — 只能重载已有运算符(不能发明 ** 或 <>)
  • 不能改变优先级和结合性 — * 永远比 + 优先级高
  • 不能改变操作数个数 — 二元运算符永远接受两个操作数
  • 至少一个操作数是用户类型 — 不能重载 int + int

成员 vs 非成员(friend)重载

struct Vec2 {
    double x, y;

    // 成员函数重载:左操作数必须是 this
    Vec2 operator+(const Vec2& rhs) const {
        return {x + rhs.x, y + rhs.y};
    }

    // 隐藏友元(hidden friend):两个操作数对称
    friend Vec2 operator*(double scalar, const Vec2& v) {
        return {scalar * v.x, scalar * v.y};
    }

    // 也支持 Vec2 * double
    friend Vec2 operator*(const Vec2& v, double scalar) {
        return {v.x * scalar, v.y * scalar};
    }
};

何时用成员 vs 非成员?

  • =、[]、()、-> — 必须是成员
  • +=、-= 等复合赋值 — 推荐成员
  • +、-、==、<< — 推荐非成员(hidden friend),确保对称性

2. 算术运算符

算术运算符重载有一个经典模式:先实现复合赋值运算符(+=),再基于它实现二元运算符(+)。

struct Vec2 {
    double x, y;

    // 第一步:实现 += (修改自身,返回引用)
    Vec2& operator+=(const Vec2& rhs) {
        x += rhs.x;
        y += rhs.y;
        return *this;
    }

    Vec2& operator-=(const Vec2& rhs) {
        x -= rhs.x;
        y -= rhs.y;
        return *this;
    }

    Vec2& operator*=(double scalar) {
        x *= scalar;
        y *= scalar;
        return *this;
    }

    // 第二步:基于 += 实现 +(返回新对象)
    friend Vec2 operator+(Vec2 lhs, const Vec2& rhs) {
        lhs += rhs;  // 复用 += 逻辑
        return lhs;  // lhs 是按值传入的副本
    }

    friend Vec2 operator-(Vec2 lhs, const Vec2& rhs) {
        lhs -= rhs;
        return lhs;
    }

    friend Vec2 operator*(Vec2 v, double scalar) {
        v *= scalar;
        return v;
    }

    friend Vec2 operator*(double scalar, Vec2 v) {
        v *= scalar;
        return v;
    }
};

为什么 operator+ 的左操作数按值传递? 因为我们需要一个副本来累加,按值传递直接获得副本,避免手动 copy。编译器还可能执行拷贝省略优化。

使用效果:

Vec2 a{1.0, 2.0};
Vec2 b{3.0, 4.0};

Vec2 c = a + b;         // {4.0, 6.0}
Vec2 d = a * 2.0;       // {2.0, 4.0}
Vec2 e = 3.0 * b;       // {9.0, 12.0}

a += b;                  // a 变为 {4.0, 6.0}

3. 比较运算符(传统方式)

在 C++20 之前,若要让类型支持全部比较操作,需要手动定义 6 个运算符:

struct Student {
    std::string name;
    int score;

    // C++17 及之前:必须逐个定义
    bool operator==(const Student& rhs) const {
        return name == rhs.name && score == rhs.score;
    }
    bool operator!=(const Student& rhs) const {
        return !(*this == rhs);
    }
    bool operator<(const Student& rhs) const {
        if (name != rhs.name) return name < rhs.name;
        return score < rhs.score;
    }
    bool operator>(const Student& rhs) const {
        return rhs < *this;
    }
    bool operator<=(const Student& rhs) const {
        return !(rhs < *this);
    }
    bool operator>=(const Student& rhs) const {
        return !(*this < rhs);
    }
};

问题显而易见:

  • 6 个函数,大量样板代码
  • 容易写错(逻辑不一致)
  • 添加新成员时容易忘记更新某个运算符
  • 对于有 N 个成员的类,字典序比较逻辑冗长且易错

4. 三向比较 <=>(C++20 Spaceship)

C++20 引入了三向比较运算符 <=>,也叫 "spaceship operator"。只需一个运算符,编译器即可自动生成全部六个比较运算符。

最简用法:= default

#include <compare>

struct Student {
    std::string name;
    int score;

    // 一行代码替代上面的 6 个函数!
    auto operator<=>(const Student&) const = default;
};

编译器自动按成员声明顺序做字典序比较:先比较 name,若相等再比较 score。同时自动生成 ==、!=、<、>、<=、>= 全部六个运算符。

Student alice{"Alice", 95};
Student bob{"Bob", 88};

alice < bob;   // true  (字典序比较 name: "Alice" < "Bob")
alice == alice; // true
alice != bob;   // true
alice >= bob;  // false

返回类型:三种 ordering

<=> 的返回值不是 bool,而是一个 ordering 类型:

返回类型 含义 典型场景
std::strong_ordering 相等的值不可区分(substitutable) int、string、大多数值类型
std::weak_ordering 等价但可能可区分 大小写不敏感字符串比较
std::partial_ordering 可能存在不可比较的值 double(NaN 与任何值都不可比)
#include <compare>

// strong_ordering:相等意味着完全相同
struct Point {
    int x, y;
    auto operator<=>(const Point&) const = default;
    // 返回 std::strong_ordering
};

// weak_ordering:等价但不一定相同
struct CaseInsensitiveString {
    std::string value;

    std::weak_ordering operator<=>(const CaseInsensitiveString& rhs) const {
        // 忽略大小写比较
        auto lower = [](std::string s) {
            std::ranges::transform(s, s.begin(), ::tolower);
            return s;
        };
        return lower(value) <=> lower(rhs.value);
    }

    bool operator==(const CaseInsensitiveString& rhs) const {
        return (*this <=> rhs) == 0;
    }
};

// partial_ordering:double 包含 NaN
struct Measurement {
    double value;

    // double 的 <=> 返回 partial_ordering
    auto operator<=>(const Measurement&) const = default;
};

自定义 spaceship:按特定成员比较

struct Employee {
    std::string name;
    int id;
    std::string department;  // 不参与比较

    // 自定义:只按 id 排序
    std::strong_ordering operator<=>(const Employee& rhs) const {
        return id <=> rhs.id;
    }

    // 自定义 <=> 时需要手动定义 ==
    bool operator==(const Employee& rhs) const {
        return id == rhs.id;
    }
};

5. == 与 <=> 的关系

C++20 中 == 和 <=> 是分开处理的,这是有意为之的设计决策:

struct LargeObject {
    std::vector<int> data;  // 可能有百万元素
    int category;

    auto operator<=>(const LargeObject&) const = default;
    // 编译器同时生成高效的 operator==
};

为什么 == 要独立于 <=>? 性能!判断两个容器是否相等时,可以先比较 size() —— 大小不同则直接返回 false,无需逐元素比较。如果 == 通过 <=> 实现,就无法做这种短路优化。

规则总结:

  • = default 的 <=> — 编译器同时生成 == 和 !=
  • 自定义的 <=> — 编译器不会自动生成 ==,你必须手动提供
  • <=> 生成 <、>、<=、>=
  • == 生成 !=
struct Config {
    std::string name;
    int priority;
    std::string comment;  // 不参与比较

    // 自定义 <=> — 只按 priority 排序
    std::strong_ordering operator<=>(const Config& rhs) const {
        return priority <=> rhs.priority;
    }

    // 必须手动定义 == !
    bool operator==(const Config& rhs) const {
        return priority == rhs.priority && name == rhs.name;
    }
};

6. 其他常见重载

operator[] — 容器下标访问

class Matrix {
    std::vector<double> data_;
    int cols_;
public:
    Matrix(int rows, int cols)
        : data_(rows * cols, 0.0), cols_(cols) {}

    // 返回引用,允许 m[{i,j}] = value
    double& operator[](std::pair<int,int> idx) {
        auto [row, col] = idx;
        return data_[row * cols_ + col];
    }

    const double& operator[](std::pair<int,int> idx) const {
        auto [row, col] = idx;
        return data_[row * cols_ + col];
    }
};

// C++23 支持多维下标:operator[](int row, int col)
// Matrix m(3, 4);
// m[1, 2] = 3.14;  // C++23

operator() — 函数对象(仿函数)

struct LinearFunction {
    double slope, intercept;

    double operator()(double x) const {
        return slope * x + intercept;
    }
};

LinearFunction f{2.0, 1.0};  // y = 2x + 1
double y = f(3.0);           // y = 7.0

// 可直接用于标准算法
std::vector<double> xs{1, 2, 3, 4, 5};
std::vector<double> ys;
std::ranges::transform(xs, std::back_inserter(ys), f);
// ys = {3.0, 5.0, 7.0, 9.0, 11.0}

operator<< — 流输出

struct Vec2 {
    double x, y;

    // 必须是非成员函数(左操作数是 ostream)
    // 使用 hidden friend 模式
    friend std::ostream& operator<<(std::ostream& os, const Vec2& v) {
        return os << "(" << v.x << ", " << v.y << ")";
    }
};

Vec2 pos{3.14, 2.72};
std::cout << "Position: " << pos << "\n";
// 输出: Position: (3.14, 2.72)

用户定义字面量 operator""

// 自定义字面量后缀
constexpr long double operator""_deg(long double degrees) {
    return degrees * std::numbers::pi_v<long double> / 180.0L;
}

constexpr unsigned long long operator""_KB(unsigned long long bytes) {
    return bytes * 1024;
}

auto angle = 90.0_deg;    // π/2
auto size  = 64_KB;       // 65536

// 标准库也提供了字面量:
using namespace std::chrono_literals;
auto timeout = 500ms;     // std::chrono::milliseconds(500)
auto delay   = 2s;        // std::chrono::seconds(2)

using namespace std::string_literals;
auto str = "hello"s;      // std::string,不是 const char*

7. 最佳实践

现代 C++ 运算符重载核心原则:

  • 最小惊讶原则 — 重载后的行为应与内置类型一致。+ 就该做加法,不要让 + 执行删除操作。
  • 对称运算符用 hidden friend — 确保 a + b 和 b + a 的隐式转换机会相同。
  • 基于复合赋值实现二元运算 — + 基于 +=、- 基于 -=,减少代码重复。
  • 优先使用 = default 的 <=> — 除非有特殊比较逻辑,否则一行搞定。
  • 自定义 <=> 时别忘了 == — 编译器不会自动生成。

完整示例:一个设计良好的值类型

#include <compare>
#include <iostream>
#include <format>

struct Vec2 {
    double x{}, y{};

    // 复合赋值运算符(成员函数)
    Vec2& operator+=(const Vec2& rhs) { x += rhs.x; y += rhs.y; return *this; }
    Vec2& operator-=(const Vec2& rhs) { x -= rhs.x; y -= rhs.y; return *this; }
    Vec2& operator*=(double s) { x *= s; y *= s; return *this; }

    // 一元运算符
    Vec2 operator-() const { return {-x, -y}; }

    // 三向比较(字典序:先 x 后 y)
    auto operator<=>(const Vec2&) const = default;

    // 二元算术运算符(hidden friend,基于 +=)
    friend Vec2 operator+(Vec2 lhs, const Vec2& rhs) { return lhs += rhs; }
    friend Vec2 operator-(Vec2 lhs, const Vec2& rhs) { return lhs -= rhs; }
    friend Vec2 operator*(Vec2 v, double s) { return v *= s; }
    friend Vec2 operator*(double s, Vec2 v) { return v *= s; }

    // 流输出
    friend std::ostream& operator<<(std::ostream& os, const Vec2& v) {
        return os << std::format("({}, {})", v.x, v.y);
    }
};

int main() {
    Vec2 a{1.0, 2.0}, b{3.0, 1.0};

    std::cout << "a + b = " << a + b << "\n";       // (4, 3)
    std::cout << "a * 3 = " << a * 3.0 << "\n";     // (3, 6)
    std::cout << "a < b = " << (a < b) << "\n";    // 1 (true)
    std::cout << "a == a = " << (a == a) << "\n";   // 1 (true)
}

避免这些常见错误:

  • 不要给运算符赋予违反直觉的语义(如用 + 做字符串格式化)
  • 不要忘记 const — 比较和算术运算符都不应修改对象
  • 不要在只需要 == 时强行实现 <=> — 如果类型没有自然顺序,只提供 == 即可
  • 不要在包含指针成员时用 = default 的 <=> — 它会比较地址而非内容

本章小结

  • 运算符重载让自定义类型具有自然的表达式语法,但必须遵循最小惊讶原则
  • 算术运算符:先实现 +=,再基于它实现 +;对称运算符用 hidden friend
  • C++20 <=>:auto operator<=>(const T&) const = default; 一行生成全部六个比较运算符
  • 三种 ordering:strong_ordering(完全相等)、weak_ordering(等价)、partial_ordering(可能不可比)
  • == 与 <=> 分离是为了性能优化;自定义 <=> 时必须手动提供 ==
  • 其他常见重载:[](下标)、()(仿函数)、<<(流输出)、""(字面量)