C++ 运算符重载
·
一、核心概念
- 运算符重载本质:把运算符(+ - * / == << >>等)封装成函数,让运算符支持自定义类对象运算,本质是函数重载。
- 目的:简化对象运算代码,符合自然阅读习惯。
- 限制:
- 不能创造新运算符;
- 不能改变运算符操作数个数(二元 + 永远两个操作数,一元!只有一个);
- 不能改变运算符优先级、结合性;
- .、.*、::、?: 这 4 个运算符禁止重载。
二、两种重载形式对比(重点)
1. 成员函数重载(类内)
语法:返回值 运算符(参数)
- 二元运算符:当前对象为左操作数,形参为右操作数,只写 1 个形参;
- 一元运算符:无参数;
- 隐含this指针代表左操作对象。 示例:obj1 + obj2 → obj1.operator+(obj2)
class Point{
int x,y;public:
// 成员重载 +
Point operator+(const Point &p)
{
return Point(x+p.x, y+p.y);
}};
2. 全局友元函数重载(全局)
语法:friend 返回值 operator运算符(参数1,参数2)
- 二元运算符:两个参数,左、右操作数各一个;
- 无this指针,必须声明为友元才能访问类私有成员; 适用场景:左操作数不是本类对象(如cout << 对象、3 + 对象)。
class Point{
int x,y;public:
friend Point operator+(const Point &a,const Point &b);};
Point operator+(const Point &a,const Point &b){
return Point(a.x+b.x,a.y+b.y);}
三、常用运算符重载分类
1. 二元算术运算符 + - * /
- 推荐:成员函数 / 友元均可;
- 规则:不修改原对象,返回新对象。
2. 关系运算符 == != >
返回bool,判断两个对象是否相等 / 大小。
friend bool operator==(Point a,Point b){
return a.x==b.x && a.y==b.y;}
3. 流运算符 <<>> 只能用友元重载
cout << 对象:左操作数是ostream,不是自定义类,不能用成员重载,必须全局友元。
#include<iostream>using namespace std;class Point{
int x,y;public:
friend ostream& operator<<(ostream &os,const Point &p);};
ostream& operator<<(ostream &os,const Point &p){
os<<"("<<p.x<<","<<p.y<<")";
return os; // 返回流对象,支持连续输出 cout<<a<<b}
4. 自增一元运算符 ++(前置 / 后置区分)
- 前置++obj:成员函数无参,先自增再返回自身
Point& operator++(){ x++;y++;return *this; }
- 后置obj++:加 int 占位参数区分,返回临时对象
Point operator++(int){
Point temp=*this;
x++;y++;
return temp;}
5. 赋值运算符 = 只能成员重载
不能用友元,默认拷贝赋值浅拷贝;有动态内存必须手动重载实现深拷贝。
Point& operator=(const Point &p){
if(this == &p) return *this; // 防止自赋值
x=p.x; y=p.y;
return *this;}
四、成员重载 vs 友元重载
- 只能成员重载:= () [] ->
- 只能友元重载:<< >>
- 两者都可以:+ - * / == != > <
- 若左操作数固定为本类对象 → 成员;
- 若左操作数是内置类型 / 流 → 友元。
五、提醒
- 重载不改变运算符原有功能,只是拓展支持类;
- 二元成员重载只 1 个形参,友元重载 2 个形参;
- 流运算符返回ostream&,赋值 / 前置 ++ 返回类名&;
- 禁止重载. :: .* ?:;
- 值传递对象会触发拷贝构造,重载形参尽量用const &节省开销。
更多推荐
所有评论(0)