-运算符重载
时间: 2025-06-12 12:45:16 浏览: 17
### C++ 运算符重载实现方法
在 C++ 中,运算符重载是一种通过定义特殊函数(称为运算符重载函数)来改变标准运算符行为的机制。这些函数可以是成员函数或非成员函数[^2]。以下是一个简单的示例,展示如何重载 `+` 运算符以实现两个自定义类对象的加法操作。
```cpp
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 重载 + 运算符
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3.5, 4.2), c2(2.1, 3.7);
Complex c3 = c1 + c2; // 调用重载的 + 运算符
c3.display(); // 输出结果为 5.6 + 7.9i
return 0;
}
```
#### Python 运算符重载使用示例
Python 中的运算符重载可以通过定义特定的魔术方法(如 `__add__`, `__sub__` 等)来实现。以下是一个示例,展示了如何重载 `+` 和 `-` 运算符以支持两个自定义类对象的操作[^1]。
```python
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
# 重载 + 运算符
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
# 重载 - 运算符
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __str__(self):
return f"({self.x}, {self.y})"
# 测试代码
v1 = Vector(3, 4)
v2 = Vector(1, 2)
v3 = v1 + v2 # 调用 __add__
v4 = v1 - v2 # 调用 __sub__
print(v3) # 输出: (4, 6)
print(v4) # 输出: (2, 2)
```
### 相关技术点总结
- 在 C++ 中,前置和后置运算符可以通过区分参数列表的方式实现。例如,`operator++()` 表示前置递增,而 `operator++(int)` 表示后置递增[^2]。
- 在 Python 中,运算符重载更加简洁,通常只需要实现对应的魔术方法即可完成复杂的功能[^4]。
阅读全文
相关推荐







