<运算符重载
时间: 2025-03-07 20:20:35 浏览: 33
### 运算符重载的概念
C++ 是少数允许运算符重载的语言之一。通过运算符重载,可以在自定义类中重新定义现有运算符的行为,使得这些运算符能够操作用户定义的数据类型[^1]。
#### C++ 中的运算符重载示例
为了更好地理解如何实现这一点,考虑一个简单的 `Complex` 类来表示复数:
```cpp
#include <iostream>
using namespace std;
class Complex {
public:
double real;
double imag;
// 构造函数
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 加法运算符重载
Complex operator+(const Complex& b) const {
return Complex(real + b.real, imag + b.imag);
}
void display() const {
cout << "(" << real << ", " << imag << ")";
}
};
int main() {
Complex c1(3.0, 4.0), c2(5.0, 6.0);
Complex sum = c1 + c2; // 使用重载后的加法运算符
sum.display();
}
```
上述代码展示了如何创建一个新的复杂数并利用已有的加号运算符执行两个复数值之间的相加操作。
#### Python 中的运算符重载
尽管 Python 不像 C++ 那样显式支持运算符重载作为语言特性的一部分,但它确实提供了特殊方法(也称为魔术方法),用于改变内置运算符对于特定类型的默认行为。例如,在 Python 的类里可以通过定义某些双下划线开头的方法名来进行类似的定制化工作。
这里有一个类似于上面例子的小型向量类 Vector 实现:
```python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self, other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2, 10)
v2 = Vector(5, -2)
print(v1 + v2)
```
这段脚本会输出 `(7, 8)` 表明成功实现了矢量间的加法计算。
阅读全文
相关推荐

















