具有私有构造函数的类的全局对象
Global object of a class with private constructor
是否可以以某种方式将全局作用域声明为类的朋友?
我面临的问题如下:
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.
}
相关文章:
- 类的全局对象和静态成员
- 内存清理程序报告全局对象构造中未初始化值的使用
- 涉及全局对象的循环依赖C++
- C++本地/全局对象的初始化
- 何时调用全局对象的构造函数?
- 不可变的全局对象应该声明为"const my_result_t BLAH"还是"extern const my_result_t BLAH;"?
- C++全局对象丢失值
- std::atexit 从全局对象的构造函数调用时的排序
- 如果 LTO 中的代码依赖于其构造的副作用,是否允许 LTO 删除未使用的全局对象?
- 从全局对象构造函数停止监视器计时器
- 全局引用全局对象
- 是否保证在销毁所有线程本地存储对象后销毁全局对象
- 销毁全局对象
- 如何在线程之间共享全局对象
- 在QT GUI中创建一个全局对象
- 使用全局对象时崩溃,但使用本地对象时不会崩溃
- C 全局对象变量内存释放
- 如何在嵌入式V8中重置全局对象
- 如何创建可供src/code和lib/libraries访问的全局对象
- 强制构造全局对象