Is it possible to do inheritance from an abstract/base struct or simulate something along those lines in C?

前端 未结 3 1780
梦谈多话
梦谈多话 2020-12-21 01:07

I am currently working with a C program that uses structs composed of xyz coordinates, but sometimes these coordinate may refer to vectors (Force/velocity type, not the data

3条回答
  •  我在风中等你
    2020-12-21 01:53

    You can use a union for this. Your main struct would contain a union of the "derived" structs as well as a "flag" field telling you which member of the union is valid:

    enum { DERIVED11, DERIVED2, DERIVED3 };
    
    struct derived1 { int x1; };
    struct derived2 { char x2; };
    struct derived3 { float x3; };
    
    struct ThreeDCartesianData
    {
       float x;
       float y;
       float z;
       int derivedType;
       union {
         struct derived1 d1;
         struct derived2 d2;
         struct derived3 d3;
       } derived;
    };
    

    Then you can use them like this:

    struct ThreeDCartesianData data1;
    data1.x=0;
    data1.y=0;
    data1.z=0;
    data1.derivedType = DERIVED1;
    data1.derived.d1.x1 = 4;
    

    You could alternately define them like this:

    struct common
    {
       int type;
       float x;
       float y;
       float z;
    };
    struct derived1
    {
       int type;
       float x;
       float y;
       float z;
       int x1;
    };
    struct derived2
    {
       int type;
       float x;
       float y;
       float z;
       char x2;
    };
    struct derived3
    {
       int type;
       float x;
       float y;
       float z;
       float x3;
    };
    
    union ThreeDCartesianData {
         struct common c;
         struct derived1 d1;
         struct derived2 d2;
         struct derived3 d3;
    };    
    

    And use them like this:

    union ThreeDCartesianData data1;
    data1.c.type=DERIVED1;
    data1.d1.x=0;
    data1.d1.y=0;
    data1.d1.z=0;
    data1.d1.x1 = 4;
    

    If all the structs in a union have an initial list elements of the same type in the same order, the standard allows you to access those fields from any of the sub-structs safely.

提交回复
热议问题