是否有可能以某种方式将全局范围声明为类的朋友?
我面临的问题如下:
class Foo
{
Foo() {}
};
Foo foo; //error: 'Foo::Foo()' is private
所以,我想要的是能够在全局范围内声明Foo
的对象,而不是在其他任何地方。
请注意,这个问题纯粹是出于问题,我并不想解决实际问题。
答案 0 :(得分:1)
不,这样做是不可能的。您只能将特定的类或功能命名为朋友。不可能将包含全局命名空间的命名空间作为朋友。
我认为没有好办法的原因是当你定义一个类或函数时,只允许一个定义(不考虑重载,这实际上是不同的函数)。但是,您可以根据需要多次打开命名空间,并且每次都会向其中添加额外的内容。因此,如果您允许访问特定的命名空间,那么任何想要输入的人都可以输入:
namespace TheNamesapceWithAccess
{
// I've got access to it here too as well as
// to the original namespace definition that was
// the only one that was intended to be allowed access.
// And I could define a function here that allows access the private thing
// from outside this namespace. I've just subverted the access restriction
// you intended.
}