Struct Inheritance in C

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

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

12条回答
  •  眼角桃花
    2020-11-29 00:49

    I like and used the idea of Typesafe inheritance in C.

    For example:

    struct Animal
    {
        int weight;
    };
    
    struct Felidae
    {
        union {
          struct Animal animal;
        } base;
        int furLength;
    };
    
    struct Leopard
    {
        union {
          struct Animal animal;
          struct Felidae felidae;
        } base;
    
        int dotCounter;
    };
    

    Usage:

    struct Leopard leopard;
    leopard.base.animal.weight = 44;
    leopard.base.felidae.furLength = 2;
    leopard.dotCounter = 99;
    

提交回复
热议问题