具有私有构造函数的类的全局对象

Global object of a class with private constructor

本文关键字:全局 对象 构造函数      更新时间:2023-10-16

是否可以以某种方式将全局作用域声明为类的朋友?

我面临的问题如下:

class Foo
{
    Foo() {}
};
Foo foo; //error: 'Foo::Foo()' is private

因此,我想要的是能够在全局范围内声明Foo的对象,而不能在其他任何地方声明。

请注意,这个问题纯粹是出于兴趣,我并不是想解决实际问题。

不,这是不可能的。您只能将特定的类或函数命名为好友。不可能使包含全局命名空间的命名空间成为好友。

我认为没有一个好的解决方案的原因是,当你定义一个类或函数时,只允许一个定义(不考虑重载,重载是真正不同的函数)。但是,您可以随意多次打开一个命名空间,每次都可以向其中添加额外的内容。因此,如果您允许访问某个特定的命名空间,任何想要访问的人都可以键入:

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.
}