Can I 'extend' a struct in C?

后端 未结 7 1465
太阳男子
太阳男子 2020-12-08 16:05
typedef struct foo_s {
    int a;
} foo;

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

Essentially I want to do:

bar b;
b.a;
<         


        
相关标签:
7条回答
  • 2020-12-08 16:55

    There is a confusion between anonymous structures and unions with nameless field. The nameless field is a Microsoft Extension.

    struct known {
        struct /* anonymous */ {
            int anonymous;
        };
        int known;
    };
    

    An anonymous struct or union is a struct or union without any tag name that is embedded within another struct or union. It does not need to have any field names either.

    A nameless field is a Microsoft Extension that allows limited inheritance in C.

    struct A {
        int a;
    };
    
    struct B {
        struct A: // nameless field
        int b;
    };
    

    Anonymous struct or union are not Nameless Fields, and Nameless Fields are not Anonymous, at least the way C11 standard defines it.

    0 讨论(0)
提交回复
热议问题