运算符重载 (3小节)
约 847 字大约 3 分钟
2026-11-11
运算符重载本质:函数重载,是C++实现静态多态的方式;只能对已有运算符重新定义,不能造新运算符。
一、运算符重载通用规则
- 不能创造新运算符,只能重载C++已有的运算符
- ❌ 禁止重载这5个:
.、.*、::、sizeof、?:三目运算符 - 不能改变:操作数个数、运算符优先级、结合性
- 重载函数,至少有一个参数是自定义类对象/引用,不能全是内置类型
- 成员函数版重载:第一个操作数就是
this指向的当前对象
二、双目运算符重载(成员函数形式)
双目:需要两个操作数,成员函数形式只需要写一个形参,另一个是
this对象 示例:+=重载
class Complex
{
public:
void display(){
cout<<"x: "<<x<<" y:"<<y<<endl;
}
Complex(int _x,int _y){
x=_x;
y=_y;
}
// 双目运算符 += 重载,成员函数版本
Complex& operator+=(const Complex& another){
this->x += another.x;
this->y += another.y;
return *this; // 返回当前对象引用,支持连续运算
}
private:
int x;
int y;
};
int main()
{
Complex c1(3,1);
Complex c2(4,5);
c1 += c2;
c1.display();
return 0;
}为什么返回引用
Complex&: 返回引用效率高,避免拷贝;支持连续链式调用(如a += b += c)
三、单目运算符重载(成员函数形式)
单目运算符:只作用于当前这一个对象,成员函数重载不需要额外形参 示例:前置
++重载
class Complex
{
public:
void display(){
cout<<"x: "<<x<<" y:"<<y<<endl;
}
Complex(int _x,int _y){
x=_x;
y=_y;
}
// 单目 ++ 前置重载
Complex& operator++(){
this->x++;
this->y++;
return *this;
}
private:
int x;
int y;
};
int main()
{
Complex c1(3,1);
++c1; // 等价 c1.operator++();
c1.display();
return 0;
}四、输入输出流运算符重载 << 和 >>
重点:流运算符不能写成类的成员函数!必须用友元函数重载 原因:
cout << obj,第一个操作数是ostream对象(cout),不是我们自定义的Complex对象,成员函数要求第一个操作数是本类对象,因此只能全局友元。
函数原型
// 输出 <<
ostream & operator << (ostream & os, 自定义类 &obj);
// 输入 >>
istream & operator >> (istream & is, 自定义类 &obj);完整示例
#include <iostream>
using namespace std;
class Complex {
public:
void display() {
cout << "x: " << x << " y: " << y << endl;
}
Complex(int _x, int _y) {
x = _x;
y = _y;
}
Complex() {}
// 声明友元
friend ostream& operator<<(ostream &os, Complex &c);
friend istream& operator>>(istream &is, Complex &c);
private:
int x;
int y;
};
// 输出重载
ostream &operator<<(ostream &os, Complex &c) {
c.display();
return os;
}
// 输入重载
istream &operator>>(istream &is, Complex &c) {
cout<<"请输入x y"<<endl;
is >> c.x >> c.y;
return is;
}
int main() {
Complex c1;
cin >> c1;
cout << c1;
return 0;
}✅ 整体总结
- 双目运算符(成员版):1个形参,左操作数是
this;比如+=、+、- - 单目运算符(成员版):0个形参,操作当前对象;比如前置
++、--、负号- - 流 << / >>:固定友元全局函数,不能做成员;返回流引用,支持链式:
cout << a << b - 返回引用的意义:减少拷贝、支持连续链式运算
- 硬性红线:
. :: .* sizeof ?:永远不能重载
📌 和前面几份笔记汇总速览
- const:只读权限
- static:类共享,脱离单个对象,无this
- 拷贝构造:对象复制,区分浅拷贝/深拷贝
- 运算符重载:给自定义类扩展运算符语法,静态多态
