Struct Inheritance in C

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

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

12条回答
  •  失恋的感觉
    2020-11-29 00:39

    The closest you can get is the fairly common idiom:

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

    As Derived starts with a copy of Base, you can do this:

    Base *b = (Base *)d;
    

    Where d is an instance of Derived. So they are kind of polymorphic. But having virtual methods is another challenge - to do that, you'd need to have the equivalent of a vtable pointer in Base, containing function pointers to functions that accept Base as their first argument (which you could name this).

    By which point, you may as well use C++!

提交回复
热议问题