Struct Inheritance in C

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

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

相关标签:
12条回答
  • 2020-11-29 00:50

    If your compiler supports anonymous structs, you can do this:

    typedef struct Base
    {
        // base members
    } Base_t;
    
    typedef struct
    {
       struct Base;  //anonymous struct
    
       // derived members
    
    } Derived_t;
    

    This way, base stuct members can be acessed directly, which is nicer.

    0 讨论(0)
  • 2020-11-29 00:52

    A slight variation to the answer of anon (and others' similar). For one level deep inheritance one can do the following:

    #define BASEFIELDS              \
        char name[NAMESIZE];        \
        char sex
    
    typedef struct {
        BASEFIELDS;
    } Person;
    
    typedef struct {
        BASEFIELDS;
        char job[JOBSIZE];
    } Employee;
    
    typedef struct {
        BASEFIELDS;
        Employee *subordinate;
    } Manager;
    

    This way the functions accepting pointer to Person, will accept pointer to Employee or Manager (with casting), same as in other answers, but in this case the initialisation will be natural as well:

    Employee e = {
        .name = "...";
        ...
    };
    

    vs

    # as in anon's answer
    Employee e = {
        .person.name = "...";
        ...
    };
    

    I believe this is how some popular projects do that (eg. libuv)

    UPDATE: also there are some good examples of similar (but not the same) concept in libsdl events implementation using structs and unions.

    0 讨论(0)
  • 2020-11-29 00:52

    You can simulate it, but you can't really inherit.

    0 讨论(0)
  • 2020-11-29 00:53

    You can do the above mentioned

    typedef struct
    {
        // base members
    
    } Base;
    
    typedef struct
    {
        Base base;
    
        // derived members
    
    } Derived;
    

    But if you want to avoid pointer casting, you can use pointers to a union of Base and Derived.

    0 讨论(0)
  • 2020-11-29 00:55

    No you cannot. C does not support the concept of inheritance.

    0 讨论(0)
  • 2020-11-29 00:56

    C has no explicit concept of inheritance, unlike C++. However, you can reuse a structure in another structure:

    typedef struct {
        char name[NAMESIZE];
        char sex;
    } Person;
    
    typedef struct {
        Person person;
        char job[JOBSIZE];
    } Employee;
    
    typedef struct {
        Person person;
        char booktitle[TITLESIZE];
    } LiteraryCharacter;
    
    0 讨论(0)
提交回复
热议问题