在 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
};
Bh (图书馆)
#include "Util.h"
class B{ /* ... complex thing */ };
Ch (图书馆)
#include "Util.h"
class C{ /* ... complex thing */ };
Dh (用户)
#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
设为私有,然后声明:-
friend class B;
friend class C;
(编辑:感谢ASH “这里不需要前向声明”。)
坏处 :-
- 这是一种
Util
以某种方式识别B
和的修改C
。
在我看来这没有意义。 - 现在 B 和 C 可以访问 的每个成员
Util
,打破任何private
访问保护。
有一种方法可以只为某些成员启用朋友,但它不是那么可爱,并且在这种情况下无法使用。 D
只是不能使用Util
,但仍然可以看到它。在.
Util
_ctrl+spaceD.h
(编辑)注意:这完全是为了编码方便;以防止一些错误或错误使用/更好的自动完成/更好的封装。这与反黑客或防止未经授权访问该功能无关。
(编辑,接受):
可悲的是,我只能接受一种解决方案,所以我主观地选择了一种需要较少工作并提供很大灵活性的解决方案。
对于未来的读者,Preet Kukreti(& texasbruce在评论)和Shmuel H.(& ASH是评论)也提供了值得一读的好解决方案。