c语言实现继承

This commit is contained in:
建峰 2024-09-01 02:46:08 +08:00
parent 5f54a63d78
commit 196c331520
2 changed files with 115 additions and 0 deletions

113
main.c
View File

@ -1,13 +1,126 @@
#include <stdint.h> #include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h> #include <stdlib.h>
#define VIRTUAL
struct _shape
{
VIRTUAL void (*area)(struct _shape *self);
VIRTUAL void (*draw)(struct _shape *self);
};
void shape_area(struct _shape *self)
{
printf("shape area\n");
}
void shape_draw(struct _shape *self)
{
printf("shape draw\n");
}
struct _shape *shape_new(void)
{
struct _shape *shape = calloc(1, sizeof(struct _shape));
return shape;
}
#if 0
void shape_free(struct _shape * self)
{
if (self != NULL)
{
free(self);
}
}
#endif
struct _rect
{
// super
// struct _shape shape;
// attribute
double width, height;
// method
void (*area)(struct _rect *self);
void (*draw)(struct _rect *self);
};
void rect_area(struct _rect *self)
{
printf("rect area = %0.2f\n", self->width * self->height);
}
void rect_draw(struct _rect *self)
{
printf("rect draw\n");
}
struct _rect *rect_new(double width, double height)
{
struct _rect *rect = calloc(1, sizeof(struct _rect));
if (rect == NULL)
{
return NULL;
}
rect->width = width;
rect->height = height;
rect->area = rect_area;
rect->draw = rect_draw;
return rect;
}
struct _circle
{
// super
// struct _shape shape;
// attribute
double radius;
// method
void (*area)(struct _circle *self);
void (*draw)(struct _circle *self);
};
void circle_area(struct _circle *self)
{
printf("circle area = %0.2f\n", 3.14 * self->radius * self->radius);
}
void circle_draw(struct _circle *self)
{
printf("circle draw\n");
}
struct _circle *circle_new(double radius)
{
struct _circle *circle = calloc(1, sizeof(struct _circle));
if (circle == NULL)
{
return NULL;
}
circle->radius = radius;
circle->area = circle_area;
circle->draw = circle_draw;
return circle;
}
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
struct _rect *rect = rect_new(4, 5);
rect->area(rect);
rect->draw(rect);
struct _circle *circle = circle_new(3);
circle->area(circle);
circle->draw(circle);
return 0; return 0;
} }

2
mk.bat
View File

@ -9,3 +9,5 @@ make -C build test
@REM cpack -C ./build/CPackConfig.cmake @REM cpack -C ./build/CPackConfig.cmake
@REM cpack -C ./build/CPackSourceConfig.cmake @REM cpack -C ./build/CPackSourceConfig.cmake
"build/release/bin/demo.exe"