#include <stdio.h>
#include <stdlib.h>
// 定义基类shape
typedef struct shape {
char *color;
} shape;
// 定义circle结构体,继承自shape
typedef struct circle {
shape base;
double radius;
} circle;
// 定义rectangle结构体,继承自shape
typedef struct rectangle {
shape base;
double length;
double width;
} rectangle;
// 初始化shape的函数
void init_shape(shape *s, const char *color) {
s->color = (char *)malloc(strlen(color) + 1);
if (s->color == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
strcpy(s->color, color);
}
// 初始化circle的函数
void init_circle(circle *c, const char *color, double radius) {
init_shape(&c->base, color);
c->radius = radius;
}
// 初始化rectangle的函数
void init_rectangle(rectangle *r, const char *color, double length, double width) {
init_shape(&r->base, color);
r->length = length;
r->width = width;
}
// 释放shape内存的函数
void free_shape(shape *s) {
free(s->color);
}
// 释放circle内存的函数
void free_circle(circle *c) {
free_shape(&c->base);
}
// 释放rectangle内存的函数
void free_rectangle(rectangle *r) {
free_shape(&r->base);
}
int main() {
circle c;
init_circle(&c, "red", 5.0);
printf("Circle: color = %s, radius = %lf\n", c.base.color, c.radius);
free_circle(&c);
rectangle r;
init_rectangle(&r, "blue", 4.0, 6.0);
printf("Rectangle: color = %s, length = %lf, width = %lf\n", r.base.color, r.length, r.width);
free_rectangle(&r);
return 0;
}