运算符重载允许为类类型定义运算符行为,如复数类中重载+和<<,使对象能直接相加和输出,提升可读性与易用性。

在C++中,运算符重载允许我们为自定义类型(如类)赋予标准运算符新的行为。通过重载,可以让对象像基本数据类型一样使用+、-、==等操作符,提升代码可读性和易用性。
什么是运算符重载
运算符重载是函数重载的一种形式,它使我们能重新定义已有运算符对类对象的操作方式。例如,两个复数对象可以通过+直接相加,而不是调用add()函数。
基本规则和限制
不是所有运算符都能被重载,比如 ::(作用域解析)、.(成员访问)、.*、?: 和 sizeof 不能重载。重载后的运算符不能改变优先级或结合性。
立即学习“C++免费学习笔记(深入)”;
- 可以作为类的成员函数或全局函数重载
- 至少有一个操作数必须是用户自定义类型
- 重载函数应保持自然语义,避免滥用
实例:复数类的加法与输出重载
下面是一个完整的例子,展示如何重载 + 和
#include <iostream>
using namespace std;
<p>class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}</p><pre class='brush:php;toolbar:false;'>// 成员函数重载加法(也可用友元或全局函数)
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// 友元函数重载输出流,访问私有成员
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << (c.imag >= 0 ? " + " : " - ") << abs(c.imag) << "i";
return os;
}};
int main() { Complex c1(3, 4); Complex c2(1, -2); Complex c3 = c1 + c2;
cout << "c1 = " << c1 << endl; cout << "c2 = " << c2 << endl; cout << "c1 + c2 = " << c3 << endl; return 0;
}
输出结果:
c1 = 3 + 4ic2 = 1 - 2i
c1 + c2 = 4 + 2i
重载赋值运算符 =
当类涉及动态资源管理时,必须自定义赋值运算符以防止浅拷贝问题:
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';
}
}
<pre class='brush:php;toolbar:false;'>// 赋值运算符重载
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; // 支持链式赋值 a = b = c
}
~String() {
delete[] data;
}
friend ostream& operator<<(ostream& os, const String& s) {
os << s.data;
return os;
}};
重载下标运算符 []
常用于实现安全的数组类访问:
class IntArray {
private:
int* arr;
int size;
public:
IntArray(int s) : size(s) {
arr = new int[size];
}
<pre class='brush:php;toolbar:false;'>// 重载[],支持读写
int& operator[](int index) {
if (index < 0 || index >= size) {
throw out_of_range("Index out of bounds");
}
return arr[index];
}
~IntArray() { delete[] arr; }};
使用示例:
IntArray a(5);a[0] = 10;
cout << a[0]; // 输出 10
基本上就这些常见用法。掌握运算符重载能让自定义类型更直观、更接近内置类型的行为,但要合理使用,避免造成误解。











