Struct Inheritance in C

后端 未结 12 1649
悲&欢浪女
悲&欢浪女 2020-11-29 00:04

Can I inherit a structure in C? If yes, how?

12条回答
  •  日久生厌
    2020-11-29 00:40

    If you want to use some gcc magic (that I would assume would work with Microsoft's C compiler) you can do something like:

    
    struct A
    {
       int member1;
    };
    
    struct B
    {
       struct A;
       int member2;
    }
    

    With gcc you can compile this with -fms-extensions (Allows for unnamed struct members like Microsofts compiler does). This is similar to the solution given by Daniel Earwicker except that it allows you to access memeber1 on a struct B instance. i.e B.member1 instead of B.A.member1.

    This is probably not the most portable approach and will not work if using a C++ compiler (different language semantics mean that it is redeclaring/defining struct A instead of instantiating it).

    If however you live in the gcc/C land only it will work and do exactly what you want.

提交回复
热议问题