复数的加减运算(运算符重载)pta
时间: 2025-05-26 22:23:01 浏览: 31
### 复数加减运算的实现
#### C++ 中的复数加减运算符重载
在 C++ 中,可以通过定义类并重载 `+` 和 `-` 运算符来实现复数的加法和减法操作。以下是具体的实现方法:
```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) {}
// 获取实部
double getReal() const { return real; }
// 获取虚部
double getImag() const { return imag; }
// 重载 "+" 运算符(友元函数)
friend Complex operator+(const Complex& c1, const Complex& c2);
// 重载 "-" 运算符(友元函数)
friend Complex operator-(const Complex& c1, const Complex& c2);
};
// 定义 "+" 的具体逻辑
Complex operator+(const Complex& c1, const Complex& c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
// 定义 "-" 的具体逻辑
Complex operator-(const Complex& c1, const Complex& c2) {
return Complex(c1.real - c2.real, c1.imag - c2.imag);
}
// 输出流重载
ostream& operator<<(ostream& os, const Complex& c) {
os << "(" << c.getReal() << ", " << c.getImag() << ")";
return os;
}
int main() {
Complex c1(3, 4); // 创建复数 (3, 4)
Complex c2(1, 2); // 创建复数 (1, 2)
Complex sum = c1 + c2; // 调用重载后的 "+"
Complex diff = c1 - c2; // 调用重载后的 "-"
cout << "Sum: " << sum << endl; // 输出 "(4, 6)"
cout << "Difference: " << diff << endl; // 输出 "(2, 2)"
return 0;
}
```
以上代码展示了如何通过友元函数的形式重载 `+` 和 `-` 运算符[^1]。
---
#### Python 中的复数加减运算符重载
Python 支持通过特殊的方法名(如 `__add__` 和 `__sub__`)来实现运算符重载。下面是一个简单的例子:
```python
class Complex:
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
def __str__(self):
return f"({self.real}, {self.imag})"
# 重载 "+" 运算符
def __add__(self, other):
if isinstance(other, Complex): # 如果另一个对象也是复数
return Complex(self.real + other.real, self.imag + other.imag)
elif isinstance(other, int) or isinstance(other, float): # 如果是与整数/浮点数相加
return Complex(self.real + other, self.imag)
else:
raise TypeError("Unsupported operand type")
# 重载 "-" 运算符
def __sub__(self, other):
if isinstance(other, Complex): # 如果另一个对象也是复数
return Complex(self.real - other.real, self.imag - other.imag)
elif isinstance(other, int) or isinstance(other, float): # 如果是与整数/浮点数相减
return Complex(self.real - other, self.imag)
else:
raise TypeError("Unsupported operand type")
# 测试代码
if __name__ == "__main__":
c1 = Complex(3, 4) # 创建复数 (3, 4)
c2 = Complex(1, 2) # 创建复数 (1, 2)
sum_result = c1 + c2 # 使用重载后的 "+"
sub_result = c1 - c2 # 使用重载后的 "-"
print(f"Sum: {sum_result}") # 输出 "(4, 6)"
print(f"Difference: {sub_result}") # 输出 "(2, 2)"
```
此代码实现了复数之间的加法和减法,并支持复数与整数或浮点数的操作[^2]。
---
#### 总结
无论是 C++ 还是 Python,在实现复数的加减运算时都需要考虑以下几点:
- **数据结构设计**:需要存储复数的实部和虚部。
- **运算符重载方式**:C++ 可以通过成员函数或友元函数实现;而 Python 则依赖于特定名称的方法(如 `__add__` 和 `__sub__`)。
- **扩展性**:可以进一步扩展到其他类型的数值计算,比如乘法、除法等。
---
阅读全文
相关推荐


















