隐藏私有数据成员? (C++)
有没有办法在 cpp 文件中向用户隐藏 C++ 类的私有数据成员? 我认为私有成员是实现的一部分,在头文件中声明它们似乎有点倒退。
Is there a way to hide private data members of a C++ class away from its users, in the cpp file? I think of the private members as part of the implementation and it seems a little backwards to declare them in the header file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
“pimpl”习语是通常处理这种情况的方式。
请参阅
The "pimpl" idiom is how this is generally handled.
See
你想使用类似于 PIMPL 习惯用法
http://en.wikipedia.org/wiki/Opaque_pointer
you want to use something like the PIMPL idiom
http://en.wikipedia.org/wiki/Opaque_pointer
请参阅 Pimpl 习语
See Pimpl Idiom
执行此操作的经典方法是使用指向实现该功能的内部类的代理指针。 据我所知,没有办法在 C++ 中进行部分类定义。
The classic way to do this is with a proxy pointer to an internal class which implements the functionality. There's no way to do partial class definitions in C++ that I know of.
商业化? ;)
您可以创建头文件,在其中仅声明公共和受保护的 API。
用户只会看到这些,他们可以包含这些。 他们将代码与您使用完整 API 和定义构建的库链接起来。
对于内联函数:确保它们在非内联代码中使用,然后库中将有一个可用的定义(但是我不确定它将内联在用户实现中)。
对于模板化代码,没有真正的解决办法。 一种半心半意的解决方案是编写代码,它使用具有不同对象类型的模板化代码。 用户将仅限于这些定义,因为它们是您的库中唯一可用的定义。
Going commercial? ;)
You can create header files, in which you only declare the public and protected API.
The user is only presented with these, which they can include. They link their code with a library, which you built using the complete API and the definitions.
For inlined functions: make sure they are used in non-inlined code, then there will be a definition available in the library (I'm not sure it will be inlined in the user implemenation, however).
For templated code there is no real way around. One half-hearted solution is to make code, which uses the templated code with different object types. The user will be limited to these, because they are the only definitions available in your library.