运算符重载允许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) {}
<pre class='brush:php;toolbar:false;'>// 重载+,返回一个新的Complex对象
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
void print() const {
cout << real << "+" << imag << "i" << 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);
};
<p>ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}</p><p>// 使用:
cout << a << " + " << b << " = " << c << endl;
// 输出:3+4i + 1+2i = 4+6i</p>3. 重载==和!=运算符
bool operator==(const Complex& other) const {
return (real == other.real) && (imag == other.imag);
}
<p>bool operator!=(const Complex& other) const {
return !(*this == other); // 复用==的结果
}</p>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';
}
}
<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;
}
~String() { delete[] data; }};
5. 重载下标[]运算符
适用于模拟数组访问行为,比如字符串或容器类。
class MyArray {
private:
int arr[10];
public:
int& operator[](int index) {
return arr[index]; // 返回引用,支持修改
}
<pre class='brush:php;toolbar:false;'>const int& operator[](int index) const {
return arr[index]; // const版本,用于只读访问
}};
// 使用: MyArray a; a[0] = 100; // 调用非const版本 cout << a[0]; // 调用const版本(如果对象是const)
基本上就这些。运算符重载是C++面向对象编程的重要特性之一,合理使用能让自定义类型的行为更加自然、贴近内置类型,提升代码可读性和可用性。掌握常见运算符的重载方法,是写出高质量C++代码的基础技能。
以上就是C++ operator重载详解_C++运算符重载实例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号