Hiding members in a C struct

前端 未结 14 2008
渐次进展
渐次进展 2020-11-29 21:02

I\'ve been reading about OOP in C but I never liked how you can\'t have private data members like you can in C++. But then it came to my mind that you could create 2 structu

14条回答
  •  Happy的楠姐
    2020-11-29 21:39

    Use the following workaround:

    #include 
    
    #define C_PRIVATE(T)        struct T##private {
    #define C_PRIVATE_END       } private;
    
    #define C_PRIV(x)           ((x).private)
    #define C_PRIV_REF(x)       (&(x)->private)
    
    struct T {
        int a;
    
    C_PRIVATE(T)
        int x;
    C_PRIVATE_END
    };
    
    int main()
    {
        struct T  t;
        struct T *tref = &t;
    
        t.a = 1;
        C_PRIV(t).x = 2;
    
        printf("t.a = %d\nt.x = %d\n", t.a, C_PRIV(t).x);
    
        tref->a = 3;
        C_PRIV_REF(tref)->x = 4;
    
        printf("tref->a = %d\ntref->x = %d\n", tref->a, C_PRIV_REF(tref)->x);
    
        return 0;
    }
    

    Result is:

    t.a = 1
    t.x = 2
    tref->a = 3
    tref->x = 4
    

提交回复
热议问题