【C++】运算符重载
目录
- 运算符重载概念
- 问题引入
- 运算符重载语法
- 运算符重载规则
- 运算符重载形式
- 类成员函数运算符重载
- 友元运算符函数重载(非类成员全局函数)
- 全局函数运算符函数重载(非友元)
- 总结
- 几种比较特殊的运算符重载
- 重载 `++`和重载`--`
- 重载`<<`和`>>`
运算符重载概念
问题引入
C++预定义中的运算符的操作对象只局限于基本的数据类型,但是对于我们自定义的类是没有办法操作的。但是大多时候我们需要对我们定义的类型进行类似的运算,这个时候就需要我们对这些运算符进行重新定义,赋予其新的功能,以满足自身的需求。
复习运算符: + - * / % ! << , >> 这些运算符只能对基本的数据类型进行操作,无法对自定义数据类型操作。
例如:
int a = 10;
int b = 20;
int sum = a + b ; //✅没问题,基本的数据类型操作
-----------------------------------------------------
struct node
{
int data;
}; //自定义数据类型struct node a;
struct node b;
struct node sum = a + b; //❌自定义类型无法运算
运算符重载语法
返回值数据类型 operator 运算符符号(参数列表)
{函数体;
}❗❗参数列表如果是对象的话,需要“类名&对象名”的形式
运算符重载规则
规则
1️⃣运算符重载不可以改变运算符原本的语义(不是语法规定,行业潜规则)
比如 加法 重载后还是将两个东西相加起来
2️⃣ 不能改变运算符的优先级 如
a + b * c;
还是乘法的优先级高3️⃣ 不能直接创建新的运算符
4️⃣ 运算符重载函数可以是成员函数,也可以是非成员函数
- 作为类成员函数时,左侧操作数必须是自定义类型(或该类型的派生类)。
- 作为非类成员函数时,通常需要通过友元函数来访问类的私有或受保护成员。
5️⃣重载的运算符函数通常具有与内置运算符相同的返回类型和参数个数:但参数类型可以是自定义类型。
可重载运算符 VS 不可重载运算符
可重载的运算符算术运算符: +, -, *, /, %, +, -, ++, --
关系运算符: ==, !=, <, >, <=, >=
逻辑运算符: &&, ||, !
位运算符: &, |, ^, ~, <<, >>
赋值运算符: =, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=
其他运算符: [], (), ->, ->*, ,, new, delete, new[], delete[]不可重载的运算符:: 域解析运算符
. 成员访问运算符
.* 成员指针访问运算符
?: 条件运算符
sizeof 运算符
运算符重载形式
类成员函数运算符重载
1️⃣成员函数形式的运算符重载是指 将运算符的重载实现为类的成员函数。这种形式适用于那些需要操作类内部数据的情况。
2️⃣ 隐式左侧操作数:
- 运算符的第一个操作数(左侧)是调用该成员函数的对象本身,通过
this
指针访问。- 对于二元运算符,函数只需要一个显式参数(右侧操作数)。
3️⃣作为类的成员函数,可以直接访问类的私有和保护成员,无需额外授权。
4️⃣ 调用方式:
对象.运算符(参数)
,如 Cat c3 = c1.operator(c2)- 或
对象 运算符 参数
语法,如 Cat c3 = c1 + c2 - 3 ;
语法:
class ClassName {
public:返回类型 operator运算符(参数) {// 实现运算符逻辑}
};
示例:重载 +
运算符
#include <iostream>
using namespace std;class Cat
{
public:Cat(int n = 0):age(n){} //构造函数void show(){cout<<age<<endl;}Cat operator+(const Cat &other){cout << "重载运算符+被调用" << endl;//返回值优化(RVO)会直接构造 Cat 到 c3,避免额外开销!return Cat(age + other.age); /*上面等价于下面:Cat temp;temp.age = age + other.age;return temp;*/}
private:int age;
};int main()
{Cat c1(10);Cat c2(5);Cat c3 = c1 + c2; //✅调用重载运算符+c3.show();return 0;
}
示例:c1+2-c2+5(返回值为对象)
#include <iostream>
using namespace std;class Cat
{
public:Cat(int n = 0):age(n){} //构造函数void show(){cout<<age<<endl;}Cat operator+(int n)//重载运算符+{cout << "重载运算符+被调用" << endl;return Cat(age + n);}Cat operator-(const Cat &other)//重载运算符-{cout << "重载运算符-被调用" << endl;return Cat(age - other.age);}
private:int age;
};int main()
{Cat c1(10);Cat c2(5);Cat c3 = c1 + 2 - c2 + 5; //✅调用重载运算符+/*函数调用形式int temp1 = c1.operator+(2);Cat temp2 = temp1.operator-(c2);Cat temp3 = temp2.operator+(5);上面的可以直接写成一行Cat c3 = c1.operator+(2).operator-(c2).operator+(5);✅写成函数调用形式*/c3.show();return 0;
}
示例:c1+2-c2+5(返回值为 int)
友元运算符函数重载(非类成员全局函数)
1️⃣ 友元函数重载运算符时,运算符被定义为一个普通函数,但它可以访问类的私有成员,因为它被
friend
关键字授予访问权限。2️⃣ 运算符的两个操作数都显式传递,不受
this
限制。3️⃣ 适用于非对称操作 ,如
int + Point
。4️⃣ 适用于
<<
和>>
,因为cout
和cin
不是类的成员。
示例:友元函数重载
class Point{
public:Point(int a,int b):x(a),y(b){}//构造函数//友元函数重载,支持int + Pointfriend Point operator+(int left,const Point& right);void display(){cout<<"x="<<x<<",y="<<y<<endl;}
private:int x,y;
};Point operator+(int left,const Point& right){return Point(left+right.x,right.y);
}int main()
{Point p1(3,4);Point p2 = 5 + p1; //调用operator+(5,p1)p2.display();//输出 x = 8 y = 4
}
全局函数运算符函数重载(非友元)
1️⃣ 全局函数重载
指的是不定义在类内部,也不声明为友元函数的运算符重载函数。2️⃣ 没有
this
指针,也不能访问类的私有成员。
示例:定义一个复数类Complex,重载运算符 (+ -),能够用于复数的加减法运算。将运算符函数重载为非成员、非友元的普通函数。编程程序,求两个复数的和 与 差。全局函数既 非成员函数 也非友元)
Complex :数据成员 实部 double real 虚部:double imag
class Complex
{
private:double real, imag;
public:Complex(double r = 0, double i = 0):real(r),imag(i){}//构造函数// ✅提供公有访问器(getter)double getReal() { return this->real; }double getImag() { return this->imag; }
};// ✅全局函数重载
Complex operator+(Complex& c1,Complex& c2)
{return Complex(c1.getReal() + c2.getReal(), c1.getImag() + c2.getImag());
}
Complex operator-(Complex& c1,Complex& c2)
{return Complex(c1.getReal() - c2.getReal(), c1.getImag() - c2.getImag());
}int main()
{Complex c1(10.0, 20.0), c2(100.0, 200.0);Complex c3 = c1 + c2;Complex c4 = c1 - c2;
}
总结
几种比较特殊的运算符重载
重载 ++
和重载--
特殊性
1️⃣ 有前置(
++i
)和后置(i++
)两种形式。2️⃣ 后置
++
需要额外参数int
来区分(这个int
只是占位,没实际作用,且必须是int
)。3️⃣ 前置
++
直接返回引用 , 后置++
返回临时对象(c++规定)。
重载后置 ++
和 --
#include <iostream>
using namespace std;class Counter
{
private:int value;
public:Counter(int v = 0):value(v){}void show(){cout << value << endl;}//✅后置++Counter operator++(int n)//int起占位作用,不代表什么作用{Counter temp = *this;//复制当前对象包括所有成员变量this->value++;//自增return temp;//返回临时对象}//✅后置--Counter operator--(int n){Counter temp = *this;--value;return temp;}
};int main()
{Counter c(10);c.show();//输出10Counter old = c++;//先返回旧值再自增old.show();//输出旧值10c.show();//输出11新值return 0;
}
重载前置 ++
和 --
class Counter {
public:int value;Counter(int v) : value(v) {}// ✅ 前置 ++Counter& operator++() {++value;return *this; // 直接返回对象本身,提高效率}// ✅ 前置 --Counter& operator--() {--value;return *this;}
};int main() {Counter c(10);++c; // 调用 operator++()cout << c.value << endl; // 输出 11
}
重载<<
和>>
1️⃣ 左操作数(cout
或 cin
)不是类的成员,无法用成员函数重载。
2️⃣ 输出运算符重载通常定义为非类成员函数(友元);输入运算符重载也通常定义为非类成员函数(友元)。将输入输出运算符定义为非类成员函数是更符合C++语言特性和使用习惯的做法。这样做可以保持运算符的通用性、灵活性、语义清晰性。
3️⃣ 返回 ostream&
或 istream&
以支持链式调用(如 cout << n1 << n2;
)。
💥<<的底层原理(>>同理)
💥 << 连续打印原理
示例:重载<<和>>
#include <iostream>
using namespace std;class Point {
private:int x, y;
public:Point() : x(0), y(0) {}// ✅ 友元函数重载 `<<`friend ostream& operator<<(ostream& os, const Point& p);// ✅ 友元函数重载 `>>`friend istream& operator>>(istream& is, Point& p);
};ostream& operator<<(ostream& os, const Point& p){os << "(" << p.x << ", " << p.y << ")";return os; // 允许链式调用}istream& operator>>(istream& is, Point& p){is >> p.x >> p.y;return is; // 允许链式调用
}int main() {Point p;cout << "输入坐标: ";cin >> p; // 用户输入: 10 20cout << "你输入的是: " << p << endl; // 输出: (10, 20)
}