|
| 1 | +#include <math.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <stdio.h> |
| 4 | + |
| 5 | +#define EPS 1e-6 |
| 6 | + |
| 7 | +typedef struct ShapeVTable { |
| 8 | + double (*area)(void *self); |
| 9 | +} ShapeVTable; |
| 10 | + |
| 11 | +typedef struct Shape { |
| 12 | + const ShapeVTable *vtable; |
| 13 | +} Shape; |
| 14 | + |
| 15 | +typedef struct { |
| 16 | + Shape base; |
| 17 | + double width; |
| 18 | + double height; |
| 19 | +} Rectangle; |
| 20 | + |
| 21 | +typedef struct { |
| 22 | + Shape base; |
| 23 | + double radius; |
| 24 | +} Circle; |
| 25 | + |
| 26 | +double rectangle_area(void *self) { |
| 27 | + Rectangle *r = (Rectangle *)self; |
| 28 | + return r->width * r->height; |
| 29 | +} |
| 30 | + |
| 31 | +double circle_area(void *self) { |
| 32 | + Circle *c = (Circle *)self; |
| 33 | + return M_PI * c->radius * c->radius; |
| 34 | +} |
| 35 | + |
| 36 | +ShapeVTable rectangle_vtable = { rectangle_area }; |
| 37 | +ShapeVTable circle_vtable = { circle_area }; |
| 38 | + |
| 39 | +Rectangle *create_rectangle(double width, double height) { |
| 40 | + Rectangle *r = malloc(sizeof(Rectangle)); |
| 41 | + r->base.vtable = &rectangle_vtable; |
| 42 | + r->width = width; |
| 43 | + r->height = height; |
| 44 | + return r; |
| 45 | +} |
| 46 | + |
| 47 | +Circle *create_circle(double radius) { |
| 48 | + Circle *c = malloc(sizeof(Circle)); |
| 49 | + c->base.vtable = &circle_vtable; |
| 50 | + c->radius = radius; |
| 51 | + return c; |
| 52 | +} |
| 53 | + |
| 54 | +double shape_area(Shape *shape) { |
| 55 | + return shape->vtable->area(shape); |
| 56 | +} |
| 57 | + |
| 58 | +int main(void) { |
| 59 | + Rectangle *rect = create_rectangle(3.0, 4.0); |
| 60 | + Circle *circ = create_circle(2.5); |
| 61 | + |
| 62 | + if (rect->base.vtable->area != rectangle_area) { |
| 63 | + fprintf(stderr, "vtable test failed: rectangle vtable does not dispatch to rectangle_area\n"); |
| 64 | + free(rect); |
| 65 | + free(circ); |
| 66 | + return 1; |
| 67 | + } |
| 68 | + if (circ->base.vtable->area != circle_area) { |
| 69 | + fprintf(stderr, "vtable test failed: circle vtable does not dispatch to circle_area\n"); |
| 70 | + free(rect); |
| 71 | + free(circ); |
| 72 | + return 1; |
| 73 | + } |
| 74 | + |
| 75 | + double rect_area = shape_area((Shape *)rect); |
| 76 | + double circ_area = shape_area((Shape *)circ); |
| 77 | + |
| 78 | + if (fabs(rect_area - 12.0) > EPS) { |
| 79 | + fprintf(stderr, "vtable test failed: rectangle area mismatch\n"); |
| 80 | + free(rect); |
| 81 | + free(circ); |
| 82 | + return 1; |
| 83 | + } |
| 84 | + double expected_circ = M_PI * 2.5 * 2.5; |
| 85 | + if (fabs(circ_area - expected_circ) > EPS) { |
| 86 | + fprintf(stderr, "vtable test failed: circle area mismatch\n"); |
| 87 | + free(rect); |
| 88 | + free(circ); |
| 89 | + return 1; |
| 90 | + } |
| 91 | + |
| 92 | + free(rect); |
| 93 | + free(circ); |
| 94 | + return 0; |
| 95 | +} |
0 commit comments