我可以在 C 中“扩展"一个结构吗? [英] Can I 'extend' a struct in C?

查看:33
本文介绍了我可以在 C 中“扩展"一个结构吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typedef struct foo_s {
    int a;
} foo;

typedef struct bar_s {
    foo;
    int b;
} bar;

基本上我想做:

bar b;
b.a;

我知道如果我在 bar 中命名了 foo 结构,我可以做 b.foo_name.a,但我不想这样做.

I know that i could do b.foo_name.a if I had named the foo struct in bar, but Id prefer not to.

有没有办法做到这一点?

Any way to do this?

这个问题得到了各种不同的答案,所以让我解释一下必要性.我想这样做的原因是因为我有一个库需要适应我的情况,这意味着我无法修改原始结构声明.此外,我需要做的就是在结构的开头添加 1 个项目(为什么是开头?因为我有一个对象"结构,它指向项目中的所有结构).我可以像你提到的那样简单地嵌入结构,但它真的很烦人,因为所有引用都需要输入'variable->image.location'那个'image'.输入十亿种类型真的很烦人.

This question has gotten a variety of different answers, so let me explain the need. The reason I want to do this is because I have a library which I need to adapt to my situation, meaning that I cant modify the original struct decleration. Furthermore, all I need to do is add 1 item to the beginning of the struct (why the beginning? because I have an 'object' struct which heads all the structs in the project). I could simply embed the struct like you mention but its REALLY annoying as all references will need to be typed 'variable->image.location' that 'image.' typed a billion types is really annoying.

推荐答案

显然此功能已添加到 C11,但可惜我无法使用最近的 C 编译器(>= GCC 4.6.2).

Evidently this feature has been added to C11, but alas I don't have access to a C compiler of recent vintage (>= GCC 4.6.2).

typedef struct foo {
  int a;
} foo;

typedef struct bar {
  struct foo;
  int b;
} bar;

int main() {
  bar b;
  b.a = 42;
  b.b = 99;
  return 0;
}

这篇关于我可以在 C 中“扩展"一个结构吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆