用c++代码写一个长方形类
时间: 2023-06-04 14:04:48 浏览: 133
好的,我可以帮您回答这个问题。以下是一个示例 C 代码,可以用来定义一个长方形类:
```
#include <stdio.h>
typedef struct {
float width;
float height;
} Rectangle;
void Rectangle_init(Rectangle* self, float width, float height) {
self->width = width;
self->height = height;
}
float Rectangle_getArea(Rectangle* self) {
return self->width * self->height;
}
int main() {
Rectangle r;
Rectangle_init(&r, 5.0, 10.0);
printf("The area of the rectangle is %.2f.\n", Rectangle_getArea(&r));
return 0;
}
```
这个代码定义了一个 Rectangle 结构体,它有两个属性:width 和 height。Rectangle_init 函数用于初始化一个 Rectangle 对象的属性值,Rectangle_getArea 函数用于计算一个 Rectangle 对象的面积。在 main 函数中,我们声明了一个 Rectangle 类型的变量 r,并且通过调用 Rectangle_init 函数来初始化它的属性。最后,我们调用 Rectangle_getArea 函数来计算该长方形的面积,并输出结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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_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)
![](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)