隐藏成员C结构 [英] Hiding members in a C struct
问题描述
我一直在阅读有关用C OOP,但我从来不喜欢你怎么不具有私有数据成员像您可以在C ++中。但随后来到了我的脑海里,你可以创建2的结构。一个是在头文件中定义,而另一个是在源文件中所定义
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 structures. One is defined in the header file and the other is defined in the source file.
// =========================================
// in somestruct.h
typedef struct {
int _public_member;
} SomeStruct;
// =========================================
// in somestruct.c
#include "somestruct.h"
typedef struct {
int _public_member;
int _private_member;
} SomeStructSource;
SomeStruct *SomeStruct_Create()
{
SomeStructSource *p = (SomeStructSource *)malloc(sizeof(SomeStructSource));
p->_private_member = 42;
return (SomeStruct *)p;
}
从这里你可以只投一种结构到其他。
这被认为是不好的做法?抑或是常做?
From here you can just cast one structure to the other. Is this considered bad practice? Or is it done often?
推荐答案
个人而言,我更喜欢这样的:
Personally, I'd more like this:
typedef struct {
int _public_member;
/*I know you wont listen, but don't ever touch this member.*/
int _private_member;
} SomeStructSource;
这是Ç毕竟,如果人们想搞砸了,他们应该被允许 - 没有必要隐瞒的东西,除了:
It's C after all, if people want to screw up, they should be allowed to - no need to hide stuff, except:
如果你需要的是保持ABI / API兼容,还有这是比较常见的,从我所看到的2的方法。
If what you need is to keep the ABI/API compatible, there's 2 approaches that's more common from what I've seen.
-
不要给你的客户端访问结构,给他们一个不透明的句柄(一个void *用pretty名),提供初始化/销毁和存取功能应有尽有。这可以确保您可以更改
结构甚至没有重新编译的客户,如果你正在编写一个库。
Don't give your clients access to the struct, give them an opaque handle (a void* with a pretty name), provide init/destroy and accessor functions for everything. This makes sure you can change the structure without even recompiling the clients if you're writing a library.
提供一个不透明的句柄作为你的结构,你可以分配但是你喜欢的一部分。这种方法即使在C ++来提供的ABI兼容性。
provide an opaque handle as part of your struct, which you can allocate however you like. This approach is even used in C++ to provide ABI compatibility.
例如
struct SomeStruct {
int member;
void* internals; //allocate this to your private struct
};
这篇关于隐藏成员C结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!