Is there any workaround for making a structure member somehow 'private' in C?

后端 未结 4 1534
清歌不尽
清歌不尽 2020-12-25 08:52

I am developing a simple library in C, for my own + some friends personal use.

I am currently having a C structure with some members that should be somehow hidden fr

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-25 09:05

    Basically the idea is to rename the variables of the struct with something like a hash and write functions (that would sort of mimmic methods in OO languages) to access them. Ideally you should have function pointers to those functions in your struct so you don't have to call an external function and pass it hte struct who's members you wish to add. However function pointer syntax is not known to be the prettiest. A simple example that may clarify what was said before by Marcelo:

    struct Car {
        int _size;
        char _colour[10];
    
    };
    
    typedef struct Car Car;
    
    
    int main (int argc, char **argv) {   
        Car *myCar= malloc(sizeof(Car));
        myCar->_size=5; /* accessing it directly just to set up a value, you shold have an
                           accessor function really */
    
        printf("car size is: %i \n",getCarSize(myCar));
        free(myCar);
    }
    
    
    
    
    int getCarSize(Car *myCar) {
         return myCar->_size;
    }
    

提交回复
热议问题