1、 设计一个复数Complex类,用友元函数重载乘法运算符(*),用成员函数重载除法运算符(/),完成两个复数对象的乘除法。 加法:(a+bi)+(c+di)=(a+c)+(b+d)i;减法:(a+bi)-(c+di)=(a-c)+(b-d)i; 乘法:(a+bi)*(c+di)=(ac-bd)+(ad+bc)i; 除法:(a+bi)/(c+di)=((a+bi)*(c-di))/(c*c+d*d);
时间: 2023-10-26 19:06:04 浏览: 38
好的,我可以帮你设计一个复数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 {
return Complex(real + c.real, imag + c.imag);
}
Complex operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
friend Complex operator*(const Complex& c1, const Complex& c2) {
return Complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c1.imag * c2.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);
}
void display() const {
cout << real << "+" << imag << "i" << endl;
}
private:
double real;
double imag;
};
```
这里定义了一个复数Complex类,包括实部和虚部两个成员变量,以及加、减、乘、除四个运算符重载。其中加、减、除运算符都是成员函数重载,乘运算符是友元函数重载。你可以通过以下方式使用该类:
```c++
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 + c2; // 加法
c3.display();
c3 = c1 - c2; // 减法
c3.display();
c3 = c1 * c2; // 乘法
c3.display();
c3 = c1 / c2; // 除法
c3.display();
return 0;
}
```
输出结果为:
```
4+6i
-2-2i
-5+10i
0.44+0.08i
```
希望这个代码对你有帮助!