用C++设计一个表示举行的类Rectangle,其数据成员函数为长Length和宽Width,设计构造函数,析构函数,显示信息的函数,求面积函数和周长函数操作,并用指针建立对象测试类
时间: 2023-06-02 13:03:27 浏览: 54
好的,我明白了。以下是回答:
可以,请看以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Rectangle {
float length;
float width;
} Rectangle;
Rectangle* createRectangle(float length, float width) {
Rectangle* rectangle = (Rectangle*)malloc(sizeof(Rectangle));
if (rectangle == NULL) {
printf("Failed to allocate memory for rectangle.\n");
exit(1);
}
rectangle->length = length;
rectangle->width = width;
return rectangle;
}
void destroyRectangle(Rectangle* rectangle) {
free(rectangle);
}
void displayRectangle(Rectangle* rectangle) {
printf("Length: %.2f\n", rectangle->length);
printf("Width: %.2f\n", rectangle->width);
}
float area(Rectangle* rectangle) {
return rectangle->length * rectangle->width;
}
float perimeter(Rectangle* rectangle) {
return 2 * (rectangle->length + rectangle->width);
}
int main() {
Rectangle* rectangle = createRectangle(5, 10);
printf("Rectangle information:\n");
displayRectangle(rectangle);
printf("Area: %.2f\n", area(rectangle));
printf("Perimeter: %.2f\n", perimeter(rectangle));
destroyRectangle(rectangle);
return 0;
}
```
这段代码定义了一个名为 `Rectangle` 的结构体,其中包含长 `length` 和宽 `width` 两个数据成员。`createRectangle` 函数为该结构体定义了一个构造函数,`destroyRectangle` 函数为该结构体定义了一个析构函数,`displayRectangle` 函数用于显示该结构体的信息,`area` 函数用于计算该结构体的面积, `perimeter` 函数用于计算该结构体的周长。
在 `main` 函数中,我们使用 `createRectangle` 函数建立了一个 `Rectangle` 类的对象,并使用 `displayRectangle` 函数和 `area` 函数和 `perimeter` 函数分别展示了类的信息、面积和周长。最后,我们使用 `destroyRectangle` 函数删除了该对象和函数。
相关推荐
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.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)