运算符重载允许C++中自定义类型使用+、-、==等操作,通过重定义运算符行为实现类对象的直观操作,提升代码可读性与实用性。

在C++中,运算符重载是一种允许我们为自定义类型(如类或结构体)赋予标准运算符特殊行为的机制。通过运算符重载,我们可以让对象像基本数据类型一样使用+、-、==、
什么是运算符重载
运算符重载的本质是函数重载。它允许我们重新定义C++中已有运算符的操作方式,但不能创建新的运算符,也不能改变运算符的优先级和结合性。
例如,对于一个表示复数的类,我们希望可以直接用+来相加两个复数对象:
Complex a(3, 4); Complex b(1, 2); Complex c = a + b; // 希望能这样写
这就需要对+运算符进行重载。
立即学习“C++免费学习笔记(深入)”;
运算符重载的语法形式
运算符重载可以通过成员函数或非成员函数(通常是友元函数)实现。
成员函数形式:
返回类型 operator@(参数列表) {
// 实现逻辑
}
非成员函数形式(常用于需要左操作数不是当前类的情况,如
返回类型 operator@(const 类名& 左, const 类名& 右) {
// 实现逻辑
}
其中@代表要重载的运算符,比如+, -, ==,
常见运算符重载实例
1. 重载+运算符(成员函数)
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 重载+,返回一个新的Complex对象
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
void print() const {
cout zuojiankuohaophpcnzuojiankuohaophpcn real zuojiankuohaophpcnzuojiankuohaophpcn "+" zuojiankuohaophpcnzuojiankuohaophpcn imag zuojiankuohaophpcnzuojiankuohaophpcn "i" zuojiankuohaophpcnzuojiankuohaophpcn endl;
}};
// 使用示例:
Complex a(3, 4);
Complex b(1, 2);
Complex c = a + b;
c.print(); // 输出:4+6i
2. 重载
因为左操作数是ostream对象,无法作为成员函数定义在Complex类中,所以通常用友元函数实现。
class Complex {
// ... 同上
friend ostream& operator<<(ostream& os, const Complex& c);
};
ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}
// 使用:
cout << a << " + " << b << " = " << c << endl;
// 输出:3+4i + 1+2i = 4+6i
3. 重载==和!=运算符
bool operator==(const Complex& other) const {
return (real == other.real) && (imag == other.imag);
}
bool operator!=(const Complex& other) const {
return !(*this == other); // 复用==的结果
}
4. 重载赋值运算符=
当类包含动态资源时(如指针),必须显式重载赋值运算符以防止浅拷贝问题。
class String {
private:
char* data;
public:
String(const char* str = nullptr) {
if (str) {
data = new char[strlen(str)+1];
strcpy(data, str);
} else {
data = new char[1];
data[0] = '\0';
}
}
// 赋值运算符重载
String& operator=(const String& other) {
if (this == &other) return *this; // 自赋值检查
delete[] data; // 释放原有内存
data = new char[strlen(other.data) + 1];
strcpy(data, other.data);
return *this;
}
~String() { delete[] data; }};
5. 重载下标[]运算符
适用于模拟数组访问行为,比如字符串或容器类。
class MyArray {
private:
int arr[10];
public:
int& operator[](int index) {
return arr[index]; // 返回引用,支持修改
}
const int& operator[](int index) const {
return arr[index]; // const版本,用于只读访问
}};
// 使用:
MyArray a;
a[0] = 100; // 调用非const版本
cout
注意事项与规则
- 不能重载的运算符有:.(成员访问)、.*(成员指针解引用)、::(作用域解析)、?:(三目运算符)、sizeof
- 重载运算符应尽量保持其原有语义,避免滥用导致代码难以理解
- 某些运算符(如=、[]、()、->)只能作为成员函数重载
- 对于二元运算符,若左操作数需要支持隐式转换,建议使用非成员函数重载
- 重载时注意返回值类型和是否需要返回引用(如赋值运算符应返回*this的引用)
基本上就这些。运算符重载是C++面向对象编程的重要特性之一,合理使用能让自定义类型的行为更加自然、贴近内置类型,提升代码可读性和可用性。掌握常见运算符的重载方法,是写出高质量C++代码的基础技能。










