蓝色天空网mbsky.com · 知识 · 实践 · 创造C++ · 本地阅读预览
教程 / 编程语言 / C++

C++ 重载运算符和重载函数

讲解同一作用域内函数重载决策规则、成员与非成员运算符重载写法、可重载与不可重载运算符边界以及 9 类常见运算符重载场景。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

重载决策与函数重载规则

C++ 允许在同一作用域中为同名函数或运算符提供多个不同实现,分别称为函数重载与运算符重载。调用时,编译器依据实参的类型、数量与顺序在候选集中挑选最佳匹配版本,这一编译期静态过程称为重载决策(Overload Resolution)。

声明重载函数时,各同名函数的形参列表(参数个数、类型或顺序)必须存在差异;仅靠返回类型不同不能构成合法重载。例如 `printData::print` 可分别提供 `int`、`double` 与字符数组三个版本,分别处理整数 `5`、浮点数 `500.263` 与字符串 `"Hello C++"`。

运算符重载语法与成员/非成员对比

运算符重载本质是名为 `operator@`(`@` 为目标符号)的特殊函数,使自定义类型能以直观表达式参与运算。多数运算符既可写为类成员函数(如 `Box operator+(const Box&) const;` 隐含左操作数 `*this`),也可写为普通或友元非成员函数(如 `Box operator+(const Box&, const Box&);` 显式接收双操作数,常用于支持对称隐式转换或流运算符 `<<` / `>>`)。

成员版 `Box::operator+` 将当前对象 `this` 与右操作数 `b` 的长宽高分别相加并返回新 `Box`;例如 `Box1(6,7,5)`(体积 210)与 `Box2(12,13,10)`(体积 1560)相加得到 `Box3(18,20,15)`(体积 5400)。

可重载/不可重载运算符边界与典型场景

C++ 大多数内置运算符都允许重载(按类别汇总见下表一),但运算符优先级、结合性与操作数个数不可更改。明确不可重载的符号包括:成员访问 `.`、成员指针访问 `.*`(注意 `->*` 实际在标准中可重载,部分传统教材一并列为慎用/不可重定义对象)、作用域解析 `::`、长度查询 `sizeof`、条件三目 `?:` 以及预处理符号 `#`/`##`。

实际工程中常见的九大运算符重载类别汇总见下表二,涵盖一元、二元、关系、输入/输出、前后置自增自减、赋值、`()` 函数对象、`[]` 下标以及 `->` 智能指针成员访问;其中 `=`、`()`、`[]`、`->` 只能作为非静态成员函数重载。

C++ 可重载运算符分类一览

类别可重载运算符符号
双目算术运算符+、-、*、/、%
关系运算符==、!=、<、>、<=、>=
逻辑运算符||、&&、!(重载 &&/|| 将失去短路求值特性,工程极少重载)
单目运算符+(正)、-(负)、*(解引用)、&(取地址)
自增自减运算符++、--(以哑元 int 区分后置版本)
位运算符|、&、~、^、<<、>>(<< 与 >> 常重载为流插入/提取)
赋值运算符=、+=、-=、*=、/=、%=、&=、|=、^=、<<=、>>=
空间申请与释放new、delete、new[]、delete[]
其他运算符()(函数调用)、->(成员访问)、,(逗号)、[](下标)

九类高频运算符重载主题索引

序号运算符重载主题与关键签名要点
1一元运算符重载:如 operator-() const,不修改原对象返回取反副本。
2二元运算符重载:如 Box operator+(const Box&) const,按语义组合双操作数。
3关系运算符重载:如 friend bool operator==(const Box&, const Box&),保持自反/对称/传递。
4输入/输出运算符重载:必须写为非成员(常为 friend),返回流引用支持链式 << / >>。
5++ 和 -- 运算符重载:前置 operator++() 返回引用,后置 operator++(int) 返回旧值副本。
6赋值运算符重载:成员 operator=(const T&),需防范自赋值并返回 *this 引用。
7函数调用运算符 () 重载:构造仿函数(Functor),常配合 STL 算法与线程入口使用。
8下标运算符 [] 重载:通常成对提供非 const 与 const 版本以支持读写与只读访问。
9类成员访问运算符 -> 重载:返回底层指针或可继续钻取的代理对象,是智能指针基石。

验证函数重载决策及二元/流/一元/前后置自增/赋值/下标/调用/箭头运算符重载

cpp · 阅读源码
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

class PrintData {
public:
    std::string format(int i) const { return "int:" + std::to_string(i); }
    std::string format(double f) const {
        std::ostringstream oss;
        oss << "double:" << std::fixed << std::setprecision(3) << f;
        return oss.str();
    }
    std::string format(const char* c) const { return std::string("str:") + c; }
};

class Box {
public:
    Box(double l = 0.0, double b = 0.0, double h = 0.0) : length_(l), breadth_(b), height_(h) {}
    double getVolume() const { return length_ * breadth_ * height_; }

    Box operator+(const Box& rhs) const {
        return Box(this->length_ + rhs.length_, this->breadth_ + rhs.breadth_, this->height_ + rhs.height_);
    }

    friend bool operator==(const Box& a, const Box& b) {
        return a.length_ == b.length_ && a.breadth_ == b.breadth_ && a.height_ == b.height_;
    }

    friend std::ostream& operator<<(std::ostream& os, const Box& b) {
        return os << static_cast<int>(b.getVolume());
    }
private:
    double length_, breadth_, height_;
};

class Counter {
public:
    explicit Counter(int v = 0) : val_(v) {}
    Counter operator-() const { return Counter(-val_); }
    Counter& operator++() { ++val_; return *this; }
    Counter operator++(int) { Counter old(*this); ++val_; return old; }
    Counter& operator=(const Counter& rhs) {
        if (this != &rhs) {
            val_ = rhs.val_;
        }
        return *this;
    }
    int get() const { return val_; }
private:
    int val_;
};

struct Payload {
    int score = 95;
};

class SmartArray {
public:
    int data[3] = {10, 20, 30};
    Payload payload;

    int& operator[](std::size_t idx) { return data[idx]; }
    int operator()(int mul) const { return (data[0] + data[1] + data[2]) * mul; }
    Payload* operator->() { return &payload; }
};

int main() {
    // 1. Function overload resolution by parameter type
    PrintData pd;
    char text[] = "Hello C++";
    std::string act1 = pd.format(5) + "|" + pd.format(500.263) + "|" + pd.format(text);
    const std::string exp1 = "int:5|double:500.263|str:Hello C++";
    bool ok1 = (act1 == exp1);

    // 2. Member binary operator+ and non-member friend operator== / operator<<
    Box b1(6.0, 7.0, 5.0);
    Box b2(12.0, 13.0, 10.0);
    Box b3 = b1 + b2;
    Box expected_b3(18.0, 20.0, 15.0);
    std::ostringstream oss;
    oss << b1 << "," << b2 << "," << b3 << ",eq=" << ((b3 == expected_b3) ? "1" : "0");
    std::string act2 = oss.str();
    const std::string exp2 = "210,1560,5400,eq=1";
    bool ok2 = (act2 == exp2);

    // 3. Unary -, prefix ++, postfix ++, and copy assignment operator=
    Counter c(5);
    Counter neg = -c;
    Counter pre = ++c;   // c becomes 6, pre is 6
    Counter post = c++;  // post is 6, c becomes 7
    Counter assigned;
    assigned = c;
    std::string act3 = "neg=" + std::to_string(neg.get()) +
                       ",pre=" + std::to_string(pre.get()) +
                       ",post=" + std::to_string(post.get()) +
                       ",after=" + std::to_string(assigned.get());
    const std::string exp3 = "neg=-5,pre=6,post=6,after=7";
    bool ok3 = (act3 == exp3);

    // 4. operator[], operator(), and operator->
    SmartArray sa;
    sa[1] = 25;
    int scaled_sum = sa(2);
    int score = sa->score;
    std::string act4 = "sub=" + std::to_string(sa[1]) +
                       ",call=" + std::to_string(scaled_sum) +
                       ",arrow=" + std::to_string(score);
    const std::string exp4 = "sub=25,call=130,arrow=95";
    bool ok4 = (act4 == exp4);

    std::cout << "{\n"
              << "  \"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\",\n"
              << "  \"cases\": [\n"
              << "    {\"name\": \"function_overload_resolution\", \"expected\": \"" << exp1
              << "\", \"actual\": \"" << act1 << "\", \"passed\": " << (ok1 ? "true" : "false") << "},\n"
              << "    {\"name\": \"binary_and_stream_operators\", \"expected\": \"" << exp2
              << "\", \"actual\": \"" << act2 << "\", \"passed\": " << (ok2 ? "true" : "false") << "},\n"
              << "    {\"name\": \"unary_inc_and_assignment_operators\", \"expected\": \"" << exp3
              << "\", \"actual\": \"" << act3 << "\", \"passed\": " << (ok3 ? "true" : "false") << "},\n"
              << "    {\"name\": \"subscript_call_and_arrow_operators\", \"expected\": \"" << exp4
              << "\", \"actual\": \"" << act4 << "\", \"passed\": " << (ok4 ? "true" : "false") << "}\n"
              << "  ]\n"
              << "}\n";
    return 0;
}
预期结果 · 待实际运行核验
  • 在 G++ 13.3.0 C++17 离线容器中验证 printData 重载、Box+ 体积 5400 与流输出、前后置 ++ 与赋值、[]/()/-> 全部 4 组实验通过。
验证函数重载决策及二元/流/一元/前后置自增/赋值/下标/调用/箭头运算符重载

所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

当前源码 SHA256:f7c33fcd4c57d4a33d232ae52f541e4581048ffa6ad2fd1c8fd8a0183105e900

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载C++ 重载运算符和重载函数实验

所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

ZIP SHA256:2e3c98bfb48452a612994906a5f6c439a60176e9df43df419109f0615d426f56

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 C++ 中如何区分前置 `++obj` 与后置 `obj++` 运算符重载函数?为什么前置通常比后置更高效?

展开参考解答

前置写作 `T& operator++()` 不带参数并直接返回递增后的 `*this` 引用;后置写作 `T operator++(int)` 通过无名 `int` 哑元区分,需要额外保存并返回递增前的对象副本,因此复杂迭代器上前置通常开销更小。

规范与官方依据