用c++实现:定义一个复数类Complex,重载运算符“+”,“”,“*”,“P,使之能用于复数的加、减、乘、除。运算符重载函数作为Complex类的成员函数。编程序,分别求两个复数之和、差、积、商。提示:注意复数的乘、除法计算。
时间: 2024-01-13 19:04:03 浏览: 80
好的,我可以回答这个问题。以下是用C++实现的复数类Complex,其中重载了运算符“+”,“-”,“*”,“/”,以实现复数的加、减、乘、除:
```c++
#include <iostream>
using namespace std;
class Complex {
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) { }
Complex operator+(const Complex& c) const;
Complex operator-(const Complex& c) const;
Complex operator*(const Complex& c) const;
Complex operator/(const Complex& c) const;
void show() const { cout << real << "+" << imag << "i" << endl; }
private:
double real;
double imag;
};
Complex Complex::operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex Complex::operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
Complex Complex::operator*(const Complex& c) const {
double r = real * c.real - imag * c.imag;
double i = real * c.imag + imag * c.real;
return Complex(r, i);
}
Complex Complex::operator/(const Complex& c) const {
double r = (real * c.real + imag * c.imag) / (c.real * c.real + c.imag * c.imag);
double i = (imag * c.real - real * c.imag) / (c.real * c.real + c.imag * c.imag);
return Complex(r, i);
}
int main() {
Complex c1(1.0, 2.0);
Complex c2(3.0, 4.0);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
Complex c5 = c1 * c2;
Complex c6 = c1 / c2;
c3.show();
c4.show();
c5.show();
c6.show();
return 0;
}
```
上述代码中,Complex类实现了构造函数、四种运算符重载(加、减、乘、除)和一个show()方法来打印出结果。在main函数中,我们创建了两个复数c1和c2,然后使用运算符重载来计算它们的和、差、积和商,并使用show()方法打印结果。
当然,这个实现还有一些可以改进的地方,比如可以重载输出运算符“<<”来更方便地输出复数等等。但是,以上代码已经可以实现复数的加、减、乘、除了。
阅读全文