1、 设计一个复数Complex类,用友元函数重载乘法运算符(*),用成员函数重载除法运算符(/),完成两个复数对象的乘除法。 [图片]实验分析和总结
时间: 2024-02-22 20:55:43 浏览: 16
当我们设计一个复数类时,可以考虑使用双精度浮点数作为实部和虚部的数据类型。同时,为了方便起见,我们可以重载输出运算符(<<)以输出复数对象的值。
下面是一个简单的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& a, const Complex& b) {
double r = a.real * b.real - a.imag * b.imag;
double i = a.real * b.imag + a.imag * b.real;
return Complex(r, i);
}
// 成员函数重载除法运算符
Complex operator/(const Complex& other) const {
double r = (real * other.real + imag * other.imag) / (other.real * other.real + other.imag * other.imag);
double i = (imag * other.real - real * other.imag) / (other.real * other.real + other.imag * other.imag);
return Complex(r, i);
}
// 重载输出运算符
friend ostream& operator<<(ostream& out, const Complex& c) {
out << c.real << " + " << c.imag << "i";
return out;
}
};
```
在上面的代码中,我们定义了一个Complex类,其中包含实部和虚部两个数据成员。我们使用了构造函数来初始化这两个数据成员。然后,我们使用友元函数重载了乘法运算符,成员函数重载了除法运算符,并重载了输出运算符以便于输出复数对象的值。
接下来,我们可以使用这个类来完成两个复数对象的乘除法。例如:
```c++
int main() {
Complex a(1, 2);
Complex b(2, -1);
Complex c = a * b;
Complex d = a / b;
cout << "a * b = " << c << endl;
cout << "a / b = " << d << endl;
return 0;
}
```
在上面的代码中,我们定义了两个复数对象a和b,并分别初始化它们的实部和虚部。然后,我们使用重载的乘法运算符计算它们的乘积,并使用重载的除法运算符计算它们的商。最后,我们使用重载的输出运算符输出结果。
输出结果如下:
```
a * b = 4 + 3i
a / b = 0.2 + 1.4i
```
可以看到,我们成功地使用了Complex类完成了两个复数对象的乘除运算。