设计一个非成员函数作为该类的友元函数, 该函数的功能输出复数对象的实部和虚部用C++的知识
时间: 2023-05-31 12:07:54 浏览: 78
非常简单,可以按照以下方式实现:
```
#include <stdio.h>
typedef struct {
double real;
double imag;
} complex;
complex add(complex a, complex b) {
complex result;
result.real = a.real + b.real;
result.imag = a.imag + b.imag;
return result;
}
void printComplex(complex c) {
printf("%.2f + %.2fi\n", c.real, c.imag);
}
// 友元函数,输出复数对象的实部和虚部
void printParts(complex c) {
printf("实部:%.2f\n", c.real);
printf("虚部:%.2f\n", c.imag);
}
int main() {
complex a = {1.0, 2.0};
complex b = {3.0, 4.0};
complex c = add(a, b);
printComplex(c);
printParts(c);
return 0;
}
```
在本例中,我们定义了一个复数 struct,并实现了一个 non-member 函数 add,用于计算两个复数的和。接着,我们定义了一个友元函数 printParts,用于输出复数对象的实部和虚部。最后,我们在 main 函数中分别调用了 printComplex 和 printParts。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)