Hiding members in a C struct

前端 未结 14 2031
渐次进展
渐次进展 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条回答
  •  旧时难觅i
    2020-11-29 21:41

    Related, though not exactly hiding.

    Is to conditionally deprecate members.

    Note that this works for GCC/Clang, but MSVC and other compilers can deprecate too, so its possible to come up with a more portable version.

    If you build with fairly strict warnings, or warnings as errors, this at least avoids accidental use.

    // =========================================
    // in somestruct.h
    
    #ifdef _IS_SOMESTRUCT_C
    #  if defined(__GNUC__)
    #    define HIDE_MEMBER __attribute__((deprecated))
    #  else
    #    define HIDE_MEMBER  /* no hiding! */
    #  endif
    #else
    #  define HIDE_MEMBER
    #endif
    
    typedef struct {
      int _public_member;
      int _private_member  HIDE_MEMBER;
    } SomeStruct;
    
    #undef HIDE_MEMBER
    
    
    // =========================================
    // in somestruct.c
    #define _IS_SOMESTRUCT_C
    #include "somestruct.h"
    
    SomeStruct *SomeStruct_Create()
    {
      SomeStructSource *p = (SomeStructSource *)malloc(sizeof(SomeStructSource));
      p->_private_member = 42;
      return (SomeStruct *)p;
    }
    

提交回复
热议问题