1. 运算符重载基础概念
在C++编程中,运算符重载(Operator Overloading)是一项强大的特性,它允许我们为自定义数据类型定义运算符的行为。简单来说,就是让+、-、*、/等运算符能够作用于我们自定义的类对象上。
运算符重载的核心思想是:通过函数重载的方式,为运算符赋予新的含义。当我们重载一个运算符时,实际上是在定义一个特殊的成员函数或友元函数,这个函数决定了该运算符在特定类对象上的行为。
注意:运算符重载不能改变运算符的优先级和结合性,也不能创建新的运算符,只能重载C++中已经存在的运算符。
运算符重载的语法形式有两种:
- 作为成员函数重载
- 作为友元函数或普通函数重载
下面是一个简单的示例,展示如何为自定义的Complex类重载+运算符:
cpp复制class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// 成员函数形式重载+
Complex operator+(const Complex& rhs) const {
return Complex(real + rhs.real, imag + rhs.imag);
}
};
1.1 可重载运算符列表
C++中大部分运算符都可以被重载,但有几个例外:
- 作用域解析运算符(::)
- 成员访问运算符(.)
- 成员指针访问运算符(.*)
- 条件运算符(?:)
- sizeof运算符
- typeid运算符
可重载的运算符包括:
- 算术运算符:+、-、*、/、%、++、--
- 关系运算符:==、!=、<、>、<=、>=
- 逻辑运算符:&&、||、!
- 位运算符:&、|、^、~、<<、>>
- 赋值运算符:=、+=、-=、*=、/=、%=、&=、|=、^=、<<=、>>=
- 其他运算符:[]、()、->、,、new、delete、new[]、delete[]
1.2 运算符重载的限制
虽然运算符重载很强大,但也有一些限制需要注意:
- 不能改变运算符的优先级和结合性
- 不能改变运算符的操作数个数(一元运算符只能有一个操作数,二元运算符只能有两个操作数)
- 不能创建新的运算符符号
- 某些运算符(=, [], (), ->)必须作为成员函数重载
- 重载运算符时,至少有一个操作数必须是用户定义的类型
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 常见运算符重载案例解析
2.1 算术运算符重载
算术运算符是最常被重载的运算符之一。让我们通过一个完整的Vector类示例来展示如何重载+、-、*等运算符。
cpp复制class Vector {
private:
double x, y, z;
public:
Vector(double x = 0, double y = 0, double z = 0) : x(x), y(y), z(z) {}
// 向量加法
Vector operator+(const Vector& rhs) const {
return Vector(x + rhs.x, y + rhs.y, z + rhs.z);
}
// 向量减法
Vector operator-(const Vector& rhs) const {
return Vector(x - rhs.x, y - rhs.y, z - rhs.z);
}
// 向量点乘
double operator*(const Vector& rhs) const {
return x * rhs.x + y * rhs.y + z * rhs.z;
}
// 向量数乘
Vector operator*(double scalar) const {
return Vector(x * scalar, y * scalar, z * scalar);
}
// 输出向量
friend std::ostream& operator<<(std::ostream& os, const Vector& v);
};
// 重载<<运算符用于输出
std::ostream& operator<<(std::ostream& os, const Vector& v) {
os << "(" << v.x << ", " << v.y << ", " << v.z << ")";
return os;
}
提示:对于对称的二元运算符(如+、*等),通常建议作为非成员函数重载,以支持左操作数也能进行隐式类型转换。
2.2 关系运算符重载
关系运
