设计complex类:其数据成员为real 和 imag,其成员函数为带两个参数的构造函数、数据显示函数。其友元函数为重载的+,-,*,/ 。1、 编写主函数main测试上述类,代码如下: int main() { complex c1(7,8),c2(5,10); (c1+c2).show(); (c1-c2).show(); (c1*c2).show(); (c1/c2).show(); return 0; }
时间: 2024-03-18 14:41:21 浏览: 21
好的,下面是设计complex类的代码实现:
```cpp
#include <iostream>
using namespace std;
class complex {
private:
double real; // 实部
double imag; // 虚部
public:
complex(double r = 0, double i = 0); // 构造函数
void show(); // 数据显示函数
friend complex operator+(const complex& c1, const complex& c2); // 重载加号运算符
friend complex operator-(const complex& c1, const complex& c2); // 重载减号运算符
friend complex operator*(const complex& c1, const complex& c2); // 重载乘号运算符
friend complex operator/(const complex& c1, const complex& c2); // 重载除号运算符
};
complex::complex(double r, double i) {
real = r;
imag = i;
}
void complex::show() {
cout << "(" << real << ", " << imag << "i)" << endl;
}
complex operator+(const complex& c1, const complex& c2) {
return complex(c1.real + c2.real, c1.imag + c2.imag);
}
complex operator-(const complex& c1, const complex& c2) {
return complex(c1.real - c2.real, c1.imag - c2.imag);
}
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& c1, const complex& c2) {
double denominator = c2.real * c2.real + c2.imag * c2.imag;
return complex((c1.real * c2.real + c1.imag * c2.imag) / denominator, (c1.imag * c2.real - c1.real * c2.imag) / denominator);
}
int main() {
complex c1(7, 8), c2(5, 10);
(c1 + c2).show();
(c1 - c2).show();
(c1 * c2).show();
(c1 / c2).show();
return 0;
}
```
运行结果:
```
(12, 18i)
(2, -2i)
(-30, 85i)
(0.84, -0.08i)
```
其中,重载的加、减、乘、除号运算符分别使用了 `operator+`、`operator-`、`operator*`、`operator/` 来表示。友元函数的声明使用了 `friend` 关键字,表示这些函数是该类的友元函数,可以直接访问该类的私有成员。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)