Hiding members in a C struct

前端 未结 14 1999
渐次进展
渐次进展 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条回答
  •  無奈伤痛
    2020-11-29 21:36

    My solution would be to provide only the prototype of the internal struct and then declare the definition in the .c file. Very useful to show C interface and use C++ behind.

    .h :

    struct internal;
    
    struct foo {
       int public_field;
       struct internal *_internal;
    };
    

    .c :

    struct internal {
        int private_field; // could be a C++ class
    };
    

    Note: In that case, the variable have to be a pointer because the compiler is unable to know the size of the internal struct.

提交回复
热议问题