小编JEv*_*ich的帖子

在 C 中转换为“超类”并返回到 C 中是否违反了严格别名?

我试图弄清楚是否在 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)

c struct strict-aliasing language-lawyer

5
推荐指数
1
解决办法
256
查看次数

标签 统计

c ×1

language-lawyer ×1

strict-aliasing ×1

struct ×1