#include typedef struct Point {int x,y;} Point; typedef struct Figure { void (*draw) (struct Figure*); void (*move) (struct Figure*, int dx, int dy); } Figure; typedef struct Circle { struct Figure base; // Circle "extends" Figure int x,y; int rad; } Circle; typedef struct Rectangle { struct Figure base; // Rectangle "extends" Figure int x,y; int width, height; } Rectangle; typedef struct Triangle { struct Figure base; // Triangle "extends" Figure Point verts[3]; } Triangle; /// Figure "Interface" /////////////////////////////////////////////// void draw_circle(Figure *self){ Circle *circle = (Circle*) self; printf("Circle: center=[%d,%d], radius=%d\n", circle->x, circle->y, circle->rad); } void draw_rectangle(Figure *self){ Rectangle *rect = (Rectangle*) self; printf("Rectangle: x=%d, y=%d], width=%d, height=%d\n", rect->x, rect->y, rect->width, rect->height); } void draw_triangle(Figure *self){ Triangle *t = (Triangle*) self; printf("Triangle: "); for (int i = 0; i < 3; i++){ printf("v%d=[%d,%d], ", i+1, t->verts[i].x, t->verts[i].y); } printf("\n"); } void move_circle(Figure *self, int dx, int dy){ Circle *circle = (Circle*) self; circle->x += dx; circle->y += dy; } void move_rectangle(Figure *self, int dx, int dy){ Rectangle *rect = (Rectangle*) self; rect->x += dx; rect->y += dy; } void move_triangle(Figure *self, int dx, int dy){ Triangle *t = (Triangle*) self; for (int i = 0; i < 3; i++){ t->verts[i].x += dx; t->verts[i].y += dy; } } ////////////////////////////////////////////////////////////////////// void draw_all(Figure **figures){ while (*figures){ (*figures)->draw(*figures); figures++; } } void move_all(Figure **figures, int dx, int dy){ printf("\nMoving all figures by %d in x and %d in y\n\n", 2, 3); while (*figures){ (*figures)->move(*figures, dx, dy); figures++; } } int main(){ Circle c = { .base = (Figure){ .draw = draw_circle, .move = move_circle }, .x = 12, .y = 12, .rad = 5 }; Rectangle rect = { .base = (Figure){ .draw = draw_rectangle, .move = move_rectangle }, .x = 34, .y = 36, .width = 23, .height = 90 }; Triangle t = { .base = (Figure) { .draw = draw_triangle, .move = move_triangle }, .verts = { {12,12}, {13,13}, {14,14} } }; Figure *arr[] = {(Figure*)&c, (Figure*)&rect, (Figure*)&t, NULL}; draw_all(arr); move_all(arr, 2, 3); draw_all(arr); return 0; }