Hiding members in a C struct

前端 未结 14 2028
渐次进展
渐次进展 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:40

    Something similar to the method you've proposed is indeed used sometimes (eg. see the different varities of struct sockaddr* in the BSD sockets API), but it's almost impossible to use without violating C99's strict aliasing rules.

    You can, however, do it safely:

    somestruct.h:

    struct SomeStructPrivate; /* Opaque type */
    
    typedef struct {
      int _public_member;
      struct SomeStructPrivate *private;
    } SomeStruct;
    

    somestruct.c:

    #include "somestruct.h"
    
    struct SomeStructPrivate {
        int _member;
    };
    
    SomeStruct *SomeStruct_Create()
    {
        SomeStruct *p = malloc(sizeof *p);
        p->private = malloc(sizeof *p->private);
        p->private->_member = 0xWHATEVER;
        return p;
    }
    

提交回复
热议问题