有no feature that control visibility/accessibility of class in C++ .
有什么办法可以造假吗?
是否有任何 C++ 的宏/模板/魔法可以模拟最接近的行为?
情况是这样的
Util.h(库)
class Util{
//note: by design, this Util is useful only for B and C
//Other classes should not even see "Util"
public: static void calculate(); //implementation in Util.cpp
};
B.h(图书馆)
#include "Util.h"
class B{ /* ... complex thing */ };
C.h(图书馆)
#include "Util.h"
class C{ /* ... complex thing */ };
D.h(用户)
#include "B.h" //<--- Purpose of #include is to access "B", but not "Util"
class D{
public: static void a(){
Util::calculate(); //<--- should compile error
//When ctrl+space, I should not see "Util" as a choice.
}
};
我糟糕的解决方案
将 Util
的所有成员设为私有(private),然后声明:-
friend class B;
friend class C;
(编辑:感谢 A.S.H“这里不需要前向声明”。)
缺点:-
- 它是一个修改
Util
以某种方式识别B
和C
。
我认为这没有意义。 - 现在 B 和 C 可以访问
Util
的每个成员,打破任何private
访问守卫。
有 a way to enable friend for only some members但它不是那么可爱,不能用于这种情况。 D
就是不能用Util
,但是还是可以看到。
在D.h
中使用自动完成(例如 ctrl+space)时,Util
仍然是一个选择。
(编辑)注意: 这一切都是为了方便编码;防止一些错误或错误使用/更好的自动完成/更好的封装。这与反黑客或防止未经授权访问该功能无关。
(编辑,接受):
遗憾的是,我只能接受一种解决方案,所以我主观地选择了需要较少工作并提供更多灵 active 的解决方案。
对于 future 的读者,Preet Kukreti(& texasbruce 在评论中)和 Shmuel H.(& A.S.H是评论)也提供了很好的解决方案,值得一读。
最佳答案
我认为最好的方法是根本不在公共(public) header 中包含 Util.h
。
为此,#include "Util.h"
仅在cpp
文件中执行:
lib.cpp
:
#include "Util.h"
void A::publicFunction()
{
Util::calculate();
}
通过这样做,您可以确保更改 Util.h
只会对您的库文件产生影响,而不会对库的用户产生影响。
此方法的问题是无法在您的公共(public) header (A.h
、B.h
)中使用 Util
。前向声明可能是这个问题的部分解决方案:
// Forward declare Util:
class Util;
class A {
private:
// OK;
Util *mUtil;
// ill-formed: Util is an incomplete type
Util mUtil;
}
关于c++ - 如何在 C++ 中伪造 "visibility of class"(不是函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41646109/