用C++语言写出 要采用面向对象的程序设计方法实现对复数类型数据进行加、减、乘、除、平方和立方运算的复数计算器
时间: 2023-11-11 15:02:35 浏览: 81
下面是一个简单的实现:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Complex {
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
Complex(const Complex& c) {
real = c.real;
imag = c.imag;
}
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
Complex operator*(const Complex& c) const {
return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
Complex operator/(const Complex& c) const {
double denominator = c.real * c.real + c.imag * c.imag;
return Complex((real * c.real + imag * c.imag) / denominator, (imag * c.real - real * c.imag) / denominator);
}
Complex operator^(int n) const {
if (n == 2) {
return Complex(real * real - imag * imag, 2 * real * imag);
} else if (n == 3) {
return Complex(real * real * real - 3 * real * imag * imag, 3 * real * real * imag - imag * imag * imag);
} else {
return Complex();
}
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}
friend istream& operator>>(istream& is, Complex& c) {
is >> c.real >> c.imag;
return is;
}
private:
double real, imag;
};
int main() {
Complex c1, c2;
cin >> c1 >> c2;
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
Complex c5 = c1 * c2;
Complex c6 = c1 / c2;
Complex c7 = c1 ^ 2;
Complex c8 = c1 ^ 3;
cout << c1 << " + " << c2 << " = " << c3 << endl;
cout << c1 << " - " << c2 << " = " << c4 << endl;
cout << c1 << " * " << c2 << " = " << c5 << endl;
cout << c1 << " / " << c2 << " = " << c6 << endl;
cout << c1 << "^2 = " << c7 << endl;
cout << c1 << "^3 = " << c8 << endl;
return 0;
}
```
这个程序定义了一个 `Complex` 类表示复数,包括实部和虚部两个成员变量,以及加、减、乘、除、平方、立方操作。其中 `operator+`、`operator-`、`operator*`、`operator/` 都是重载运算符实现的。`operator^` 实现了平方和立方运算。这个程序还重载了输入和输出运算符,可以直接从输入流中读取复数,或者将复数输出到输出流中。在 `main` 函数中,我们可以读取两个复数,进行加、减、乘、除、平方、立方运算,并将结果输出到标准输出流中。
阅读全文