Mimic classes in ANSI C
To make a struct's members "priv开发者_开发技巧ate" to the outside I know that I can do this.
In the .h file
typedef struct Obj Obj;
In the .c file you then
struct Obj {
int a;
int b;
}
This will keep the knowledge of the existense of a
and b
from beeing known. But all the "member" functions in the .c file will now about them and can opperate on then.
But what I wonder about now is that if you can make PART of the struct "private". Say that I want to keep those a
and b
variables "private" but then I want to have some function pointers that I want to remain public. Is this possible?
I know that if I try to declare these in the struct in the .h file I would get a duplicate declaration error on the struct.
Copy Python: use the honour system for ‘private’ members.
Put a _
at the start of the member name as a red flag that other code shouldn't be touching it. Unless you've got security boundaries inside your application (which is uncommon), you don't actually need real privates, you only need a convention agreed-upon by members of your team to pretend they're private.
Try not to add complexity by forcing C into a paradigm which it doesn't really fit. Extra headers for public/private interfaces and extra source files for class management are going to make your development work more complicated, defeating the ‘more maintainable’ goal that information-hiding is aiming for.
Could this (not tested or even compiled) work for you?
in the file "everybody_includes_me.h":
typedef public_struct {
func1_ptr;
func2_ptr;
} PUBLIC_STRUCT;
extern PUBLIC_STRUCT func_pointers;
and in the file "totally_public.c":
PUBLIC_STRUCT func_pointers;
then in the file "all_private.c":
struct Obj { PUBLIC_STRUCT *func_pointers; int a; int b; }
精彩评论