隐藏私有数据成员?(C++)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/206272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:42:56  来源:igfitidea点击:

Hiding private data members? (C++)

c++classprivate

提问by Jeff Linahan

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.

有没有办法在 cpp 文件中隐藏 C++ 类的私有数据成员,使其远离用户?我认为私有成员是实现的一部分,在头文件中声明它们似乎有点倒退。

回答by Kristopher Johnson

The "pimpl" idiom is how this is generally handled.

“pimpl”成语是通常处理这种情况的方式。

See

回答by Keith Nicholas

you want to use something like the PIMPL idiom

你想使用像 PIMPL 成语这样的东西

http://en.wikipedia.org/wiki/Opaque_pointer

http://en.wikipedia.org/wiki/Opaque_pointer

回答by Nemanja Trifunovic

回答by Nick

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.

执行此操作的经典方法是使用指向实现该功能的内部类的代理指针。据我所知,没有办法在 C++ 中进行部分类定义。

回答by Nick

Going commercial? ;)

商业化?;)

You can create header files, in which you only declare the public and protected API.

您可以创建头文件,在其中仅声明公共和受保护的 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.

用户只会看到这些,他们可以包含这些。他们将代码与您使用完整 API 和定义构建的库相关联。

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.

对于模板化代码,没有真正的解决方法。一种半心半意的解决方案是编写代码,它使用具有不同对象类型的模板化代码。用户将仅限于这些,因为它们是您的库中唯一可用的定义。