【C++】数据结构:抽象定义复数,并实现复数的加、减、乘、除四则运算,用complex写
时间: 2024-09-15 07:08:46 浏览: 64
数据结构课程参考习题(I)1
在C++中,可以使用内置的`<complex>`库来方便地处理复数。这个库提供了一个名为`complex`的数据类型,用于表示复数。下面是如何使用`complex`定义一个复数并实现基本算术操作的一个简单示例:
```cpp
#include <iostream>
#include <complex>
// 定义复数类
class ComplexNumber {
public:
// 构造函数
std::complex<double> c; // 使用complex双精度类型存储实部和虚部
// 构造复数
ComplexNumber(double real = 0, double imag = 0) : c(real, imag) {}
// 加法
ComplexNumber operator+(const ComplexNumber& other) const {
return ComplexNumber(c.real() + other.c.real(), c.imag() + other.c.imag());
}
// 减法
ComplexNumber operator-(const ComplexNumber& other) const {
return ComplexNumber(c.real() - other.c.real(), c.imag() - other.c.imag());
}
// 乘法
ComplexNumber operator*(const ComplexNumber& other) const {
double real = c.real() * other.c.real() - c.imag() * other.c.imag();
double imag = c.real() * other.c.imag() + c.imag() * other.c.real();
return ComplexNumber(real, imag);
}
// 除法,这里假设除数不为零
ComplexNumber operator/(const ComplexNumber& other) const {
double denominator = other.c.real() * other.c.real() + other.c.imag() * other.c.imag();
return ComplexNumber((c.real() * other.c.real() + c.imag() * other.c.imag()) / denominator,
(c.imag() * other.c.real() - c.real() * other.c.imag()) / denominator);
}
// 输出复数
void print() const {
std::cout << "Complex Number (" << c.real() << ", " << c.imag() << "i)" << std::endl;
}
};
int main() {
ComplexNumber a(2, 3);
ComplexNumber b(4, -1);
ComplexNumber sum = a + b;
ComplexNumber diff = a - b;
ComplexNumber prod = a * b;
ComplexNumber quot = a / b;
std::cout << "Sum: ";
a.print();
b.print();
sum.print();
std::cout << "\nDifference: ";
a.print();
b.print();
diff.print();
std::cout << "\nProduct: ";
a.print();
b.print();
prod.print();
std::cout << "\nQuotient (assuming non-zero denominator): ";
a.print();
b.print();
quot.print();
return 0;
}
```
在这个例子中,我们首先定义了一个`ComplexNumber`类,它包含一个`std::complex<double>`类型的成员变量`c`。然后实现了加、减、乘、除四种运算符重载,以及一个打印复数的方法。在`main()`函数里,创建了两个复数对象并进行了相应的计算。
阅读全文