设计一个复数Complex类,用友元函数重载乘法运算符(*),用成员函数重载除法运算符(/),完成两个复数对象的乘除法。(用c++写)
时间: 2024-03-02 12:49:31 浏览: 17
好的,以下是复数Complex类的设计,其中包括重载乘法运算符和除法运算符的实现:
```c++
#include <iostream>
using namespace std;
class Complex {
private:
double real; // 实部
double imag; // 虚部
public:
Complex(double r = 0.0, double i = 0.0): real(r), imag(i) {}
friend Complex operator*(const Complex& lhs, const Complex& rhs);
Complex operator/(const Complex& rhs);
void print() const {
cout << real << " + " << imag << "i" << endl;
}
};
Complex operator*(const Complex& lhs, const Complex& rhs) {
double r = lhs.real * rhs.real - lhs.imag * rhs.imag;
double i = lhs.real * rhs.imag + lhs.imag * rhs.real;
return Complex(r, i);
}
Complex Complex::operator/(const Complex& rhs) {
double divisor = rhs.real * rhs.real + rhs.imag * rhs.imag;
double r = (real * rhs.real + imag * rhs.imag) / divisor;
double i = (imag * rhs.real - real * rhs.imag) / divisor;
return Complex(r, i);
}
int main() {
Complex a(1.0, 2.0);
Complex b(3.0, 4.0);
Complex c = a * b;
c.print(); // 输出 -5 + 10i
Complex d = a / b;
d.print(); // 输出 0.44 + 0.08i
return 0;
}
```
在类中定义了两个私有成员变量,分别表示实部和虚部。为了方便,我们在构造函数中添加了默认参数。接着,我们用友元函数重载了乘法运算符,用成员函数重载了除法运算符。最后,我们定义了一个输出函数 print() 来打印复数的值。
使用方法:
1. 创建两个复数对象 a 和 b。
2. 用乘法运算符 * 计算它们的积,结果保存在新的复数对象 c 中。
3. 调用 c 的 print() 函数输出积的值。
4. 用除法运算符 / 计算它们的商,结果保存在新的复数对象 d 中。
5. 调用 d 的 print() 函数输出商的值。
输出结果:
```
-5 + 10i
0.44 + 0.08i
```
可以看到,该程序成功地实现了复数对象的乘除法运算。