pta定义一个复数类 complex
时间: 2025-05-25 09:50:54 浏览: 20
### 复数类 `Complex` 的实现
以下是基于提供的引用内容以及复数类的要求所设计的一个完整的 C++ 实现方案:
#### 类定义部分
```cpp
class Complex {
private:
int real; // 实部
int imag; // 虚部
public:
// 构造函数,默认参数设置为0
Complex(int r = 0, int i = 0) : real(r), imag(i) {}
// 复制构造函数
Complex(const Complex& c) : real(c.real), imag(c.imag) {}
// 显示复数的方法
void Display() const {
if (imag >= 0) {
printf("%d+%di\n", real, imag);
} else {
printf("%d%di\n", real, imag); // 自动处理负号
}
}
// 获取实部和虚部的值(用于计算)
int GetReal() const { return real; }
int GetImag() const { return imag; }
};
```
此部分实现了复数类的核心功能,包括私有成员变量、带有默认参数的构造函数、复制构造函数以及显示复数的功能。
---
#### 加法函数 `AddComplex`
为了支持两个复数相加,可以定义一个外部函数 `AddComplex`,它接受两个复数对象作为常量引用参数并返回一个新的复数对象表示它们的和。
```cpp
// 函数 AddComplex:实现两个复数相加
Complex AddComplex(const Complex& a, const Complex& b) {
int sum_real = a.GetReal() + b.GetReal();
int sum_imag = a.GetImag() + b.GetImag();
return Complex(sum_real, sum_imag);
}
```
通过这种方式,我们能够高效地利用传入的对象而不会修改原始数据[^1]。
---
#### 主函数示例
下面是一个简单的主函数,展示如何创建复数实例并通过调用相应方法完成基本操作。
```cpp
#include <iostream>
using namespace std;
int main() {
int r1, i1, r2, i2;
// 输入第一个复数
cin >> r1 >> i1;
Complex c1(r1, i1);
// 输入第二个复数
cin >> r2 >> i2;
Complex c2(r2, i2);
// 输出两个复数
cout << "First complex number: ";
c1.Display(); // 使用Display打印c1
cout << "Second complex number: ";
c2.Display(); // 使用Display打印c2
// 计算并输出两者的和
Complex result = AddComplex(c1, c2);
cout << "Sum of the two complex numbers: ";
result.Display();
return 0;
}
```
这段代码展示了从标准输入读取两个复数值的过程,并演示了如何使用之前定义好的类及其辅助函数来执行必要的逻辑运算[^2]。
---
#### 特殊情况考虑
当涉及到字符串形式化表达时,需特别关注零值情形下的格式调整。例如,在 Java 中提供了专门针对这种情况优化过的 `toString()` 方法[^4]。对于本案例中的C++版本,则可通过条件判断语句灵活控制输出样式以适应不同场景需求。
---
###
阅读全文
相关推荐











