#include <stdio.h>
typedef void(*Draw)();
typedef struct
{
Draw draw;
}Shape;
typedef struct
{
Shape shape;
int radius;
}Circle;
typedef struct
{
Shape shape;
int length;
int width;
}Rectangle;
void drawCircle()
{
printf("Drawing a circle\n");
}
void drawRectangle()
{
printf("Drawing a rectangle\n");
}
int main(void)
{
Circle circle;
circle.shape.draw = drawCircle;
circle.radius = 2;
Rectangle rectangle;
rectangle.shape.draw = drawRectangle;
rectangle.length = 3;
rectangle.width = 2;
Shape* shape[] = { (Shape*)&circle ,(Shape*)&rectangle};
for (int i = 0; i < sizeof(shape) / sizeof(shape[0]); i++)
{
shape[i]->draw();
}
return 0;
}
运行结果