Structures and casting in C

前端 未结 8 1490
野性不改
野性不改 2020-12-16 02:07

I was wondering:

If I have structure definitions, for example, like this:

struct Base {
  int foo;
};

struct Derived {
  int foo; // int foo is comm         


        
8条回答
  •  伪装坚强ぢ
    2020-12-16 03:02

    There is another little thing that might be helpful or related to what you are doing ..

    #define SHARED_DATA int id;
    
    typedef union base_t {
        SHARED_DATA;
        window_t win;
        list_t   list;
        button_t button;         
    }
    
    typedef struct window_t {
        SHARED_DATA;
        int something;
        void* blah;
    }
    
    typedef struct window_t {
        SHARED_DATA;
        int size;
     }
    
    typedef struct button_t {
        SHARED_DATA;
        int clicked;
     }
    

    Now you can put the shared properties into SHARED_DATA and handle the different types via the "superclass" packed into the union.. You could use SHARED_DATA to store just a 'class identifier' or store a pointer.. Either way it turned out handy for generic handling of event types for me at some point. Hope i'm not going too much off-topic with this

提交回复
热议问题