高级程序设计(C++)


运算符重载

计算机学院    杨已彪

yangyibiao@nju.edu.cn

本讲提纲

基本做法

  • 为什么需要运算符重载

  • 成员函数 vs 非成员函数

  • 双目、单目、++/--

  • []、()、->

特殊运算符

  • 赋值 =

  • new / delete

  • 类型转换与 explicit

  • 流运算符 << / >>

本讲目标

能够为自定义类型设计符合直觉的运算符,并知道哪些运算符不该重载、哪些必须作为非成员。


为什么需要运算符重载?

class Complex {
public:
    Complex(double r = 0, double i = 0)
        : re_(r), im_(i) {}

    Complex add(const Complex& other) const {
        return Complex(re_ + other.re_,
                       im_ + other.im_);
    }
private:
    double re_, im_;
};

Complex a(1, 2), b(3, 4);
Complex c = a.add(b);   // 能工作,但不像数学
目标

让自定义类型像内置类型一样自然:

Complex c = a + b;
if (a == b) { ... }
std::cout << c;

运算符重载让代码的写法贴近问题领域的语义。

本质 a + b 只是 operator+(a, b) 的另一种写法;重载的是函数,不是语法。

运算符重载的规则

可以做什么

  • 重载 C++ 已有运算符

  • 改变运算符对自定义类型的含义

  • 写成成员函数或非成员函数

  • 至少一个操作数是类/枚举类型

不能做什么

  • 发明新运算符(如 **)

  • 改变操作数个数

  • 改变优先级和结合性

  • 重载 ::、.、.*、?:、sizeof

  • 改变内置类型之间的运算含义

语义约束

语言不强制你“保持原语义”,但滥用会让代码难以理解。例如把 + 定义成“删除元素”就是灾难。


成员函数 vs 非成员函数

形式 左操作数 典型场景 例子
成员函数 必须是当前类对象 修改自身、+=、[]、() a += b
非成员函数 可以是任意类型 左操作数不是当前类 2.5 + c、cout << t
class Complex {
public:
    Complex operator+(const Complex& other) const;
};

a + b → a.operator+(b)

Complex operator+(double d, const Complex& c);

2.5 + c → operator+(2.5, c)

左操作数是 double,不可能写成 Complex 的成员函数。


双目运算符:+ 返回值

class Complex {
public:
    Complex(double r = 0, double i = 0)
        : re_(r), im_(i) {}

    Complex operator+(const Complex& other) const {
        return Complex(re_ + other.re_,
                       im_ + other.im_);
    }
private:
    double re_, im_;
};

Complex a(1, 2), b(3, 4);
Complex c = a + b;      // (4, 6)
为什么按值返回

a + b 产生一个新值,不修改 a 或 b。返回新对象是正确语义。

不要返回引用

返回局部对象的引用会悬空;返回 a 或 b 的引用会让 c = a + b 意外修改操作数。


复合赋值:+= 返回引用

class Complex {
public:
    Complex& operator+=(const Complex& other) {
        re_ += other.re_;
        im_ += other.im_;
        return *this;
    }
};

Complex a(1, 2), b(3, 4);
a += b;          // 修改 a
(a += b) += b;   // 支持连续复合赋值
设计习惯
  • 复合赋值修改左操作数

  • 返回 *this 的引用

  • a += b 通常比 a = a + b 更高效(避免临时对象)

  • 可以用 += 实现 +,减少重复

对称性

提供 + 时通常也提供 +=;提供 < 时通常也提供 >、<=、>=(C++20 可用 <=> 一次生成)。


比较运算符与三路比较

class Target {
public:
    bool operator==(const Target& other) const {
        return id_ == other.id_;
    }
    bool operator!=(const Target& other) const {
        return !(*this == other);
    }
    bool operator<(const Target& other) const {
        return priority_ < other.priority_;
    }
private:
    int id_;
    int priority_;
};
C++20:<=>
#include <compare>

class Target {
public:
    auto operator<=>(const Target&) const = default;
};

编译器自动生成 ==、!=、<、<=、>、>=,按成员依次比较。

严格弱序

用于 std::sort / std::map 的比较必须满足严格弱序:不可出现 a < b 和 b < a 同时为真。


单目运算符:- 与 !

class Complex {
public:
    Complex operator-() const {   // 取负
        return Complex(-re_, -im_);
    }

    bool operator!() const {      // 是否为零
        return re_ == 0 && im_ == 0;
    }
private:
    double re_, im_;
};

Complex a(1, 2);
Complex b = -a;     // (-1, -2)
if (!a) { ... }     // false
成员 vs 非成员
  • 单目运算符常写成成员函数

  • 也可以写成非成员:operator-(const Complex&)

  • 返回新值(取负/取反不修改原对象)

不要混淆 operator-()(单目取负)与 operator-(a, b)(双目减法)。


前置与后置 ++ / --

class Counter {
public:
    Counter& operator++() {      // 前置 ++c
        ++value_;
        return *this;
    }

    Counter operator++(int) {    // 后置 c++
        Counter old = *this;
        ++(*this);
        return old;
    }
private:
    int value_ = 0;
};

Counter c;
++c;        // 前置:返回引用
c++;        // 后置:返回旧值的副本
区分方式
  • 前置:无参数,返回 T&

  • 后置:多一个 int 参数(不使用其值),返回 T

  • 后置的 int 只是标记,不参与运算

返回值不同

前置返回引用以支持 ++(++c);后置返回旧值副本,不能返回引用(局部对象会悬空)。


下标 []:const 与非 const

class IntArray {
public:
    int& operator[](std::size_t i) {
        return data_[i];
    }
    const int& operator[](std::size_t i) const {
        return data_[i];
    }
private:
    int* data_;
    std::size_t size_;
};

IntArray a(10);
a[2] = 42;              // 非 const:可写

const IntArray& ca = a;
int x = ca[2];          // const:只读
// ca[2] = 1;           // 错误
要点
  • 返回引用,才能支持 a[i] = x

  • 提供 const 重载,常量对象才能读

  • 通常不做越界检查;需要时用 at() 抛异常

  • 下标类型常用 std::size_t

标准库 vector、string 同时提供 operator[](不检查)与 at()(检查并抛 out_of_range)。


函数调用 ():函数对象

struct GreaterThan {
    int threshold;

    bool operator()(int x) const {
        return x > threshold;
    }
};

GreaterThan gt{10};
bool b = gt(42);        // true

std::vector<int> v{5, 12, 3, 20};
auto n = std::count_if(v.begin(), v.end(), gt);
函数对象(functor)
  • 可以像函数一样调用

  • 可以携带状态(threshold)

  • 可以被 STL 算法接受

  • Lambda 本质上是编译器生成的函数对象

与函数指针

函数对象通常更容易被编译器内联,且能保存状态;现代 C++ 中 Lambda 更常用。


->:指针类与智能指针

class TargetPtr {
public:
    explicit TargetPtr(Target* p) : p_(p) {}
    Target* operator->() { return p_; }
    Target& operator*() { return *p_; }
private:
    Target* p_;
};

Target t(1, "main.o", 2);
TargetPtr p(&t);
p->priority();  // 等价于 p.operator->()->priority()
(*p).name();       // 等价于 p.operator*().name()
用途
  • 智能指针(unique_ptr、shared_ptr)

  • 迭代器

  • 代理对象:在访问成员前做额外操作(计数、日志、检查)

链式规则 operator-> 必须返回指针(或另一个重载了 -> 的对象);编译器会继续应用 -> 直到得到裸指针。

赋值运算符:复制与移动

class String {
public:
    String& operator=(const String& other) {
        if (this == &other) return *this;
        char* p = new char[other.len_ + 1];
        std::strcpy(p, other.data_);
        delete[] data_;
        data_ = p;
        len_ = other.len_;
        return *this;
    }

    String& operator=(String&& other) noexcept {
        if (this != &other) {
            delete[] data_;
            data_ = other.data_;
            len_ = other.len_;
            other.data_ = nullptr;
            other.len_ = 0;
        }
        return *this;
    }
};
要点
  • 赋值运算符只能作为成员函数

  • 返回 *this 引用

  • 处理自赋值

  • 先分配后释放,保证异常安全

  • 移动赋值标记 noexcept

拷贝/移动语义的完整讨论在第 4、5 单元;这里只强调“运算符形式”。


new / delete 重载:为什么很少用

class Target {
public:
    static void* operator new(std::size_t size) {
        std::cout << "allocate " << size << "\n";
        return ::operator new(size);
    }

    static void operator delete(void* p) {
        std::cout << "free\n";
        ::operator delete(p);
    }
};
用途
  • 自定义内存池 / 对象池

  • 调试分配行为

  • 特定对齐要求

风险

重载 new / delete 不影响构造/析构调用,但会改变内存来源;必须正确处理 new[]、对齐、失败与全局 ::operator new。初学阶段不要轻易重载。


类型转换运算符与 explicit

class Fraction {
public:
    Fraction(int n, int d) : n_(n), d_(d) {}

    explicit operator double() const {
        return static_cast<double>(n_) / d_;
    }
private:
    int n_, d_;
};

Fraction f(1, 2);
double x = static_cast<double>(f);  // OK
// double y = f;                    // 错误:explicit
隐式转换的风险

单参数构造函数和转换运算符都可能引发隐式转换,导致重载歧义或意外行为。

  • 构造函数加 explicit

  • 转换运算符加 explicit(C++11)

  • 需要转换时显式 static_cast

经典歧义 a + 1 既可以把 a 转成 int,也可以把 1 转成 A;编译器无法选择。

流运算符:必须是非成员函数

class Target {
public:
    Target(int id, std::string name)
        : id_(id), name_(std::move(name)) {}

    friend std::ostream& operator<<(std::ostream& os,
                                    const Target& t);
private:
    int id_;
    std::string name_;
};

std::ostream& operator<<(std::ostream& os, const Target& t) {
    return os << "[" << t.id_ << "] " << t.name_;
}

std::cout << t << "\n";   // [1] main.o
为什么不能是成员

a << b 如果写成成员,左操作数必须是 Target;但 std::cout << t 的左操作数是 ostream,所以只能写成非成员。

返回 ostream&

返回输出流本身,才能支持 cout << a << b << endl 的链式调用。


运算符重载的设计原则

应该重载

  • 语义与内置类型一致

  • 能显著提升可读性

  • 类型是数值、容器、迭代器、智能指针

  • 与标准库算法/容器协作需要

不应该重载

  • 语义不直观(+ 表示删除)

  • 改变 && / || 的短路语义

  • 为了“炫技”而重载

  • 让类型隐式转换到多种类型

运算符重载的目标是让代码更像领域语言,而不是让编译器接受奇怪的写法。


主线案例:Target 的运算符

class Target {
public:
    int id() const { return id_; }
    int priority() const { return priority_; }
    const std::string& name() const { return name_; }

    bool operator==(const Target& other) const {
        return id_ == other.id_;
    }
    bool operator<(const Target& other) const {
        return priority_ < other.priority();
    }
private:
    int id_;
    std::string name_;
    int priority_;
};

std::ostream& operator<<(std::ostream& os, const Target& t) {
    return os << "[" << t.id() << "] " << t.name()
              << " p=" << t.priority();
}
用途
  • operator<:放入 std::priority_queue 或 std::set

  • operator==:查找、去重

  • operator<<:日志与调试输出

访问方式

这里通过 public 的 id() / name() 访问,不需要友元;只有需要直接访问私有数据时才用友元。

如果优先级相同的任务需要稳定顺序,可以把 id 作为第二比较键。


课堂任务 9:完善 Complex

任务

实现 Complex 类,至少支持:

  • Complex(double r = 0, double i = 0)

  • operator+、operator+=

  • operator-(双目与单目取负)

  • operator==、operator!=

  • 前置/后置 operator++

  • operator<< 输出 a+bi

  • operator double() 返回模长(explicit)

在 main 中验证混合运算与输出。

验收标准
  • a + b、a += b 语义正确

  • ++a 与 a++ 返回值不同

  • a == b 与 a != b 一致

  • std::cout << a 输出可读

  • 不返回局部对象的引用

  • 编译无警告

提示

先用 += 实现 +;用 == 实现 !=;前置 ++ 返回引用,后置返回旧值。


任务 9 参考实现(一):算术与比较

class Complex {
public:
    Complex(double r = 0, double i = 0)
        : re_(r), im_(i) {}

    Complex& operator+=(const Complex& o) {
        re_ += o.re_; im_ += o.im_;
        return *this;
    }

    Complex operator+(const Complex& o) const {
        Complex tmp = *this;
        tmp += o;
        return tmp;
    }

    Complex operator-() const {
        return Complex(-re_, -im_);
    }

    bool operator==(const Complex& o) const {
        return re_ == o.re_ && im_ == o.im_;
    }
    bool operator!=(const Complex& o) const {
        return !(*this == o);
    }

private:
    double re_, im_;
};
要点
  • += 修改自身,返回 *this

  • + 复用 +=,返回新值

  • 单目 - 不修改原对象

  • != 复用 ==,保持语义一致

顺序

先实现复合赋值,再基于它实现双目运算,可以减少重复代码,也更容易保证语义一致。


任务 9 参考实现(二):自增、转换与输出

class Complex {
public:
    // ... 构造函数与算术运算符 ...

    Complex& operator++() {
        ++re_;
        return *this;
    }

    Complex operator++(int) {
        Complex old = *this;
        ++(*this);
        return old;
    }

    explicit operator double() const {
        return std::sqrt(re_ * re_ + im_ * im_);
    }

    friend std::ostream& operator<<(std::ostream& os,
                                    const Complex& c) {
        return os << c.re_
                  << (c.im_ >= 0 ? "+" : "")
                  << c.im_ << "i";
    }

private:
    double re_, im_;
};

使用

Complex a(1, 2), b(3, 4);
Complex c = a + b;
a += b;
std::cout << c << "\n";
std::cout << ++a << "\n";
std::cout << a++ << "\n";
4+6i

5+6i 5+6i

要点

  • 前置 ++ 返回引用

  • 后置 ++ 返回旧值副本

  • explicit 转换需要 static_cast

  • operator<< 返回流引用


常见陷阱

返回值/引用

  • + 返回局部对象引用 → 悬空

  • += 返回值而不是引用 → 多一次拷贝

  • 后置 ++ 返回引用 → 悬空

  • operator[] 不返回引用 → 无法赋值

语义/设计

  • 重载 && / || 破坏短路

  • 隐式转换导致重载歧义

  • 只重载 == 不重载 !=

  • operator< 不满足严格弱序

  • 把 new / delete 当普通函数随意重载

判断

如果一段代码需要写注释解释“这里的 + 其实是删除”,那这个运算符就不该重载。


课堂小测

  1. operator+ 为什么通常按值返回,而 operator+= 按引用返回?
  2. 前置 ++ 与后置 ++ 在参数和返回值上有什么区别?为什么后置版本多一个 int 参数?
  3. operator<< 为什么通常写成非成员函数?返回 ostream& 的作用是什么?
  4. 哪些运算符不能重载?为什么 && / || 的重载要特别谨慎?

小结:让类型说人话

形式
  • 成员:左操作数是本类

  • 非成员:左操作数可能是其他类型

  • 至少一个操作数是类/枚举

语义
  • + 产生新值

  • += 修改自身并返回引用

  • [] 返回引用

  • << 返回流引用

克制
  • 只重载语义直观的运算符

  • 不改变优先级与操作数个数

  • 不滥用隐式转换

  • 与标准库协作时优先满足其约定

运算符重载的最高标准:使用者不需要看实现,就能猜到它的行为。




未完待续