矩形实现
本课属于 Coddy C 学习旅程的“面向对象编程”单元。第 46 课,共 61 课。
挑战
简单让我们继续构建 Shape Drawer 项目,实现 Rectangle:这是另一个具体形状,它和 Circle 一样,内嵌了基础 Shape 结构体。
在现有项目的基础上,你将在以下文件中添加矩形功能:
shape.h:保留基础Shape接口,以及前几课中定义的DrawFunc和AreaFunc函数指针类型。circle.h和circle.c:保留上一课中的 Circle 实现。rectangle.h:在这里定义Rectangle结构体。矩形将Shape作为其第一个成员内嵌,并添加width和height字段(两者的数据类型都是double)。声明构造函数create_rectangle,接收 width 和 height 参数,并按值返回一个Rectangle。rectangle.c:实现矩形特有的行为:draw_rectangle:打印Drawing Rectangle with width: X.XX and height: X.XX(两个值都显示 2 位小数)area_rectangle:返回 width × heightcreate_rectangle:初始化一个Rectangle,将内嵌Shape的函数指针连接到矩形函数,设置尺寸,然后返回该矩形
main.c:演示如何通过同一个接口使用这两种形状。读取两个输入:矩形的 width 和 height。使用构造函数创建矩形,然后通过内嵌Shape的函数指针调用draw和area。打印面积,保留 2 位小数。
程序会接收两个输入:width 和 height 的值(浮点数)。
输入为 4.0 和 3.0 时的示例输出:
Drawing Rectangle with width: 4.00 and height: 3.00
Area: 12.00输入为 7.5 和 2.5 时的示例输出:
Drawing Rectangle with width: 7.50 and height: 2.50
Area: 18.75和 Circle 一样,Rectangle 将 Shape 作为第一个成员内嵌,因此你可以通过这个内嵌成员访问函数指针。这种一致的模式实现了多态:两种形状都可以通过 Shape 接口统一处理。记得在所有头文件中使用 include guard。
亲手试试
#include <stdio.h>
#include "shape.h"
#include "rectangle.h"
int main() {
double width, height;
scanf("%lf", &width);
scanf("%lf", &height);
// TODO: 使用 create_rectangle(width, height) 创建一个矩形
// TODO: 通过嵌入的 Shape 的函数指针调用 draw
// TODO: 通过嵌入的 Shape 的函数指针调用 area
// TODO: 将面积保留 2 位小数并输出:"Area: %.2f\n"
return 0;
}面向对象编程中的所有课
自己练习: C 在线编译器