我试图弄清楚是否在 C 中进行模拟子类化,其中超类结构批量包含在子类结构中,而不仅仅是具有相同成员前缀的子类和超类。
\n在下面的示例代码中,我试图阐明我的想法:
\n#include "stdlib.h"\n#include "stdio.h"\n#include "string.h"\n\nenum type {\n IS_A,\n IS_B,\n};\n\nstruct header {\n enum type type;\n};\n\nstruct a {\n struct header hdr;\n float x;\n};\n\nstruct b {\n struct header hdr;\n int y;\n};\n\nvoid do_with_a(struct header *obj) {\n if (obj->type == IS_A) {\n struct a *a = (struct a *)obj;\n printf("%f\\n", a->x);\n }\n}\n\nvoid do_with_b(struct header *obj) {\n // Oops forgot to check the type tag\n struct b *b = (struct b *)obj;\n printf("%d\\n", b->y);\n}\n\nint main() {\n struct a *a = malloc(sizeof(*a));\n\n …Run Code Online (Sandbox Code Playgroud)