在 C++ 中将静态类转换为命名空间时如何处理私有成员函数?
我有一个类,它有 5 个静态公共函数和 1 个静态私有函数(从其中一个公共函数调用)。该类没有任何成员变量。在我看来,它应该是一个命名空间而不是一个类。但是私有函数该怎么办呢?我不希望每个命名空间用户都可以访问它,但命名空间中没有访问控制。
I have a class that has 5 static public functions and 1 static private function (called from one of the public functions). The class doesn't have any member variables. It seems to me that it should be a namespace and not a class. But what to do with the private function? I prefer it not to be accessible by every namespace user, but there is no access control in namespaces.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我知道有两种方法
不要在标头中声明它们,
一种方法是不在标头中声明这些函数。它们只能放入实现文件中的未命名命名空间中。
事实上,您必须在实现文件中实现访问此私有函数的任何函数(而不是在标头中内联)。
将它们放入详细名称空间中
最好将它们放入不同的标头中,并包含它们。因此它们的代码不会干扰您的接口标头。
boost
也是这样做的:There are two ways i know of
Don't declare them in the header
One way is to not declare those functions inside the header. They can be placed into unnamed namespaces within the implementation file, only.
Indeed, you will then have to implement any function that accesses this private function in the implementation file (not inline in the header).
Put them into a detail namespace
Preferably, you put them in a different header, and include them. So the code of them won't disturb your interface header. This is how
boost
does it, too:我认为没有解决方案:)
一种不同的解决方案是将这些函数分离到一个单独的编译单元中,然后在匿名命名空间内声明私有函数。
I don't think there is a solution to this :)
One -different- solution, would be to separate these functions into a separate compilation unit, then declare the private functions inside an anonymous namespace.
将公共声明保留在头文件中。将实现移至 cpp 文件。将以前的
私有
方法标记为静态
。这将使它们无法从不同的链接器对象(编译单元)访问并有效地隐藏它们。Keep the public declaration in the header file. Move the implementations to a cpp file. Mark previously
private
methods asstatic
. This will make them unaccessible from a different linker objects (compilation units) and effectively hide them.在我看来它应该是一个类,而不是一个命名空间。 C++ 中的命名空间主要是名称解析工具,并不是设计的基础,也不真正提供封装。所以我会保持原样。
It seems to me it should be a class, not a namespace. Namespaces in C++ are primarily name resolution tools, and are not intended as the basis for design and do not really provide encapsulation. So I would leave it as it is.