Z
ZHANK
面向对象

运算符重载

重载 +-*/、<< 输出、[] 下标、= 赋值、前置/后置 ++

运算符重载

C++ 允许你给自己的类定义 +<<[] 等运算符的行为——让自定义类型和内置类型一样自然。

学完本章你将: 掌握成员/非成员重载、<< 输出、[] 下标、前置/后置 ++。


基本规则

cpp
#include <iostream>

class Point {
    int x, y;
public:
    Point(int x, int y) : x(x), y(y) { }

    // 成员函数重载:+
    Point operator+(const Point &other) const {
        return Point(x + other.x, y + other.y);
    }

    // 成员函数重载:==
    bool operator==(const Point &other) const {
        return x == other.x && y == other.y;
    }

    // 友元函数重载:<<(输出到流)
    friend std::ostream &operator<<(std::ostream &os, const Point &p) {
        return os << "(" << p.x << ", " << p.y << ")";
    }
};

int main() {
    Point p1(1, 2), p2(3, 4);
    Point p3 = p1 + p2;
    std::cout << p3 << "\n";        // (4, 6)
    std::cout << (p1 == p2) << "\n"; // 0 (false)
    return 0;
}

`[]` 下标重载

cpp
class Array {
    int data[10];
public:
    int &operator[](size_t i) {
        return data[i];  // 返回引用,允许修改
    }
    const int &operator[](size_t i) const {
        return data[i];  // const 版本:只读
    }
};

前置 vs 后置 ++

cpp
class Counter {
    int n;
public:
    // 前置 ++ (++c) —— 返回引用,避免拷贝
    Counter &operator++() { ++n; return *this; }

    // 后置 ++ (c++) —— 多一个 int 参数做区分
    Counter operator++(int) {
        Counter tmp = *this;
        ++n;
        return tmp;  // 返回旧值
    }
};

💡 前置 ++ 返回引用(高效),后置 ++ 返回副本(需拷贝)。能用前置就用前置。