Struct Inheritance in C

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

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

12条回答
  •  被撕碎了的回忆
    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.

提交回复
热议问题