中级篇 · 1.8 · 中级
运算符重载
让自定义类型也会「算术」
运算符重载 = 给类定义一个名为 operator运算符 的函数,让 a + b 这样的表达式也能作用于对象。本质是函数调用:a + b 等价于 a.operator+(b)(成员函数版)。
规则底线(选择题)
- 不能发明新运算符(比如自定义 **)
- 不能改变原运算符的优先级、结合性、操作数个数
- 五个运算符不可重载:
..*::?:sizeof(必背)
成员函数版 vs 全局(友元)函数版
| 场景 | 用哪种 | 原因 |
|---|---|---|
| 左操作数是本类对象 | 成员函数 | a + b 就是 a.operator+(b) |
| 左操作数是流/其他类型 | 全局函数(常配 friend) | cout << a 的左边是 ostream,不能改人家的类 |
| 对称运算如 2 + a | 全局函数 | 成员函数版处理不了左边的 int |
输出运算符 << 的标准写法
friend ostream& operator<<(ostream &os, const T &x) { os << ...; return os; } —— 左操作数是 cout,只能写成全局/友元;返回 os 引用才能链式 cout << a << b。
前置 ++ 与后置 ++(必考签名)
- 前置:
T& operator++()—— 先自增,返回自身(引用) - 后置:
T operator++(int)—— int 是占位参数只为区分;先保存旧值,自增后返回旧值副本
拷贝赋值运算符 operator= 与三法则
2-7 的拷贝构造管「新对象由旧对象出生」(Data b = a;);而 b = a;(b 已存在)走的是拷贝赋值运算符 operator=,两者是两条不同的路。管理裸指针资源的类若不重写 operator=,默认赋值仍是浅拷贝——两个对象指向同一块内存,析构时双重释放。标准写法四步:① 自赋值检查 if (this != &o);② delete 释放自己的旧资源;③ 申请新内存并逐成员复制;④ return *this;(支持链式 a = b = c)。三法则(Rule of Three):析构函数、拷贝构造、拷贝赋值三者之一需要自定义时,三个都应配套写全。
<< 写成成员函数(左操作数对不上);③ 忘记在 operator<< 末尾 return os; 导致无法链式输出。避坑指南
后置 ++ 忘记 int 占位参数
错误写法
class Counter {
public:
int v;
Counter& operator++() { v++; return *this; } // 前置
Counter& operator++() { v++; return *this; } // 重复定义,编译错误
};正确写法
class Counter {
public:
int v;
Counter& operator++() { // 前置:先加后用
v++;
return *this;
}
Counter operator++(int) { // 后置:int 占位参数
Counter old = *this;
v++;
return old; // 返回旧值
}
};两个 ++ 靠参数表区分:前置无参,后置带一个「不使用」的 int 占位参数——这是语法规定的唯一区分手段,漏写就变成同名重复定义。
把 << 重载写成成员函数
错误写法
class Point {
public:
int x, y;
ostream& operator<<(ostream &os) { // 错!
os << x << "," << y;
return os;
}
};
// 调用只能写成别扭的 point << cout,而不是 cout << point正确写法
class Point {
public:
int x, y;
friend ostream& operator<<(ostream &os, const Point &p) {
os << "(" << p.x << "," << p.y << ")";
return os;
}
};
// 现在可以自然地写:cout << p << endl;cout << p 的左操作数是 ostream 对象,成员函数版会把「自己」绑在左边(变成 p.operator<<(cout)),与使用习惯相反。所以 << 必须重载为全局函数(访问私有成员时加 friend)。
operator<< 忘记返回 os
错误写法
friend void operator<<(ostream &os, const T &x) {
os << x.v;
} // 返回 void,链式写法 cout << a << b 直接编译错误正确写法
friend ostream& operator<<(ostream &os, const T &x) {
os << x.v;
return os; // 返回流本身,才能继续 << b
}cout << a << b 从左往右结合,先算 cout << a,它的返回值还要接着 << b——所以必须返回 ostream&。
只补了拷贝构造,忘了拷贝赋值运算符
错误写法
class Data {
int* data; int size;
public:
Data(int n) : size(n) { data = new int[n]; }
~Data() { delete[] data; } // ① 析构函数有了
Data(const Data& o) : size(o.size) { // ② 拷贝构造(深拷贝)有了
data = new int[o.size];
for (int i = 0; i < size; ++i) data[i] = o.data[i];
}
// 漏了 operator= —— b = a 走默认浅拷贝!
};
// Data b(2); b = a; 两个对象指向同一块内存
// 析构时同一内存被 delete 两次 => 双重释放崩溃正确写法
Data& operator=(const Data& o) { // ③ 拷贝赋值补上
if (this != &o) { // 自赋值检查: a = a 也不出事
delete[] data; // 先释放自己的旧资源
size = o.size;
data = new int[size]; // 再申请新内存
for (int i = 0; i < size; ++i) data[i] = o.data[i];
}
return *this; // 返回 *this, 支持 a = b = c
}拷贝构造管「新对象从旧对象出生」(Data b = a;),operator= 管「两个已存在的对象之间赋值」(b = a;)。管理裸指针的类只写拷贝构造,赋值走的仍是编译器默认的逐成员浅拷贝,析构时双重释放。三法则:自定义了析构、拷贝构造、拷贝赋值之一,三个就应配套写全。
代码实践
复数类:+、+= 与 ==
运算符重载最经典的载体——复数运算:
complex.cpp
#include <iostream>
using namespace std;
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex &o) const { // 成员函数版
return Complex(real + o.real, imag + o.imag);
}
Complex &operator+=(const Complex &o) {
real += o.real;
imag += o.imag;
return *this; // 返回自身支持链式
}
bool operator==(const Complex &o) const {
return real == o.real && imag == o.imag;
}
void show() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex a(1, 2), b(3, 4);
Complex c = a + b; // 等价于 a.operator+(b)
cout << "a + b = ";
c.show();
a += b;
cout << "a += b 后 a = ";
a.show();
cout << (c == a ? "c == a" : "c != a") << endl;
return 0;
}预期输出
a + b = 4 + 6i
a += b 后 a = 4 + 6i
c == a- operator+ 返回新对象(不修改 a、b);operator+= 返回自身引用
- 参数用
const Complex&:不拷贝、不被误改 - 末尾 const 修饰成员函数表示「不修改成员」,是良好习惯
分数类:friend 重载 << 与 <
输出运算符和比较运算符的全局(友元)函数版本:
fraction.cpp
#include <iostream>
using namespace std;
class Fraction {
private:
int num, den; // 分子、分母
public:
Fraction(int n, int d) : num(n), den(d) {}
friend ostream &operator<<(ostream &os, const Fraction &f) {
os << f.num << "/" << f.den;
return os; // 返回流,支持链式
}
friend bool operator<(const Fraction &a, const Fraction &b) {
return a.num * b.den < b.num * a.den; // 交叉相乘比较
}
};
int main() {
Fraction f1(1, 2), f2(2, 3);
cout << "f1 = " << f1 << ", f2 = " << f2 << endl;
cout << (f1 < f2 ? "f1 < f2" : "f1 >= f2") << endl;
Fraction f3(3, 4);
cout << "f3 = " << f3 << endl;
cout << (f2 < f3 ? "f2 < f3" : "f2 >= f3") << endl;
return 0;
}预期输出
f1 = 1/2, f2 = 2/3
f1 < f2
f3 = 3/4
f2 < f3<<左边是 cout,只能写成全局函数;要访问私有成员所以声明 friend- 分数比较不用通分:1/2 与 2/3 交叉相乘 1×3 < 2×2 → 3 < 4 成立
- friend 是「准许访问私有成员」的通行证,写在类内、本质是全局函数
前置/后置 ++ 的完整实现
同一计数器两种自增,观察返回值差异:
inc.cpp
#include <iostream>
using namespace std;
class Counter {
private:
int v;
public:
Counter(int init = 0) : v(init) {}
Counter &operator++() { // 前置:先加,返回自己
++v;
return *this;
}
Counter operator++(int) { // 后置:int 占位参数
Counter old = *this; // 保存旧值
++v;
return old; // 返回旧值副本
}
int get() { return v; }
};
int main() {
Counter c(5);
cout << "++c 前的值: " << c.get() << endl;
++c;
cout << "++c 后的值: " << c.get() << endl;
Counter old = c++; // old 是 6,c 变 7
cout << "c++ 返回旧值: " << old.get() << endl;
cout << "c 现在的值: " << c.get() << endl;
return 0;
}预期输出
++c 前的值: 5
++c 后的值: 6
c++ 返回旧值: 6
c 现在的值: 7- 前置返回
Counter&(没有拷贝),后置返回Counter(旧值副本) - 后置多一次拷贝——这也解释了循环里习惯写
++i的原因 - 行为与内置 int 完全一致:++c 先加后用,c++ 先用后加
巩固练习
复数输出运算符 · 简单
<<,使 cout << Complex(2, 5) 输出 2 + 5i。提示
(ostream &os, const Complex &c),末尾 return os。参考解答
#include <iostream>
using namespace std;
class Complex {
private:
double real, imag;
public:
Complex(double r, double i) : real(r), imag(i) {}
friend ostream &operator<<(ostream &os, const Complex &c) {
os << c.real << " + " << c.imag << "i";
return os;
}
};
int main() {
Complex c(2, 5);
cout << "c = " << c << endl;
return 0;
}预期输出
c = 2 + 5i前后置 ++ 输出推演 · 中等
Counter c(10);
Counter x = c++; // x, c 各是多少?
Counter y = ++c; // y, c 各是多少?提示
参考解答
#include <iostream>
using namespace std;
class Counter {
private:
int v;
public:
Counter(int i = 0) : v(i) {}
Counter &operator++() { ++v; return *this; }
Counter operator++(int) { Counter old = *this; ++v; return old; }
int get() { return v; }
};
int main() {
Counter c(10);
Counter x = c++; // x = 10,c = 11
cout << "x = " << x.get() << ", c = " << c.get() << endl;
Counter y = ++c; // c = 12,y = 12
cout << "y = " << y.get() << ", c = " << c.get() << endl;
return 0;
}预期输出
x = 10, c = 11
y = 12, c = 12分数类的 == 和 + · 中等
+ 和 ==。加法按通用交叉相乘实现即可,结果不必约分——1/4 + 2/4 输出 12/16 属预期;再用 ==(交叉乘积比较)验证它与 3/4 相等。提示
参考解答
#include <iostream>
using namespace std;
class Fraction {
private:
int num, den;
public:
Fraction(int n, int d) : num(n), den(d) {}
Fraction operator+(const Fraction &o) const {
return Fraction(num * o.den + o.num * den, den * o.den);
}
bool operator==(const Fraction &o) const {
return num * o.den == o.num * den;
}
friend ostream &operator<<(ostream &os, const Fraction &f) {
os << f.num << "/" << f.den;
return os;
}
};
int main() {
Fraction a(1, 4), b(2, 4);
Fraction c = a + b;
cout << a << " + " << b << " = " << c << endl;
cout << (c == Fraction(3, 4) ? "相等" : "不等") << endl;
return 0;
}预期输出
1/4 + 2/4 = 12/16
相等Money 类的 += 与 < · 中等
+=(返回自身)与 <(成员函数)。验证:5元2角1分(521) 加 3元6分(306) 后为 827 分,且小于 9 元。提示
Money& operator+=(const Money &o) 内部 cents += o.cents 后 return *this。参考解答
#include <iostream>
using namespace std;
class Money {
private:
int cents;
public:
Money(int c = 0) : cents(c) {}
Money &operator+=(const Money &o) {
cents += o.cents;
return *this;
}
bool operator<(const Money &o) const { return cents < o.cents; }
int get() { return cents; }
};
int main() {
Money a(521), b(306);
a += b;
cout << "合计: " << a.get() << " 分" << endl;
cout << (a < Money(900) ? "不足 9 元" : "达到 9 元") << endl;
return 0;
}预期输出
合计: 827 分
不足 9 元二维向量类的运算全家桶 · 困难
+ -(成员函数)与 <<(友元),验证 (3,1)+(1,4)-(2,0) = (2,5)。提示
参考解答
#include <iostream>
using namespace std;
class Vector2D {
private:
double x, y;
public:
Vector2D(double x = 0, double y = 0) : x(x), y(y) {}
Vector2D operator+(const Vector2D &o) const {
return Vector2D(x + o.x, y + o.y);
}
Vector2D operator-(const Vector2D &o) const {
return Vector2D(x - o.x, y - o.y);
}
friend ostream &operator<<(ostream &os, const Vector2D &v) {
os << "(" << v.x << ", " << v.y << ")";
return os;
}
};
int main() {
Vector2D a(3, 1), b(1, 4), c(2, 0);
Vector2D r = a + b - c;
cout << "结果 = " << r << endl;
return 0;
}预期输出
结果 = (2, 5)延伸阅读
菜鸟教程 C++ 重载运算符
可重载运算符列表与成员/友元示例
cppreference 运算符重载
重载规则的权威文档(含不可重载清单)
Wandbox
在线验证重载后的运算符行为