cmake_demo/library/rect.c

63 lines
1.2 KiB
C

#include "rect.h"
double rect_area(void *self)
{
double area = 0;
struct _rect *pthis = *(struct _rect **)self;
// struct _rect *pthis = container_of(self, struct _rect, me);
area = pthis->shape->vtb.area(pthis);
return area;
}
void rect_draw(void *self)
{
struct _rect *pthis = container_of(self, struct _rect, me);
pthis->shape->vtb.draw(pthis);
}
double _rect_area(void *self)
{
struct _rect *pthis = (struct _rect *)self;
double area = pthis->width * pthis->height;
printf("rect area = %0.2f\n", area);
return area;
}
void _rect_draw(void *self)
{
printf("rect draw\n");
}
struct _rect *rect_new(double width, double height)
{
// super
static struct _virtual_table vtb = {
.area = (double (*)(void *self))_rect_area,
.draw = (void (*)(void *self))_rect_draw,
};
struct _shape *shape = shape_new();
if (shape == NULL)
{
return NULL;
}
shape->vtb = vtb;
// self
struct _rect *rect = calloc(1, sizeof(struct _rect));
if (rect == NULL)
{
return NULL;
}
rect->me = rect;
rect->width = width;
rect->height = height;
// set parent
rect->shape = shape;
return rect;
}