我正在尝试实现这个单例类。但我遇到了这个错误:
'Singleton ::〜Singleton':无法访问在类'Singleton'中声明的私有成员 这在头文件中被标记,最后一行包含闭括号。
有人能帮我解释一下这个问题是什么原因吗? 以下是我的源代码。
Singleton.h:
class Singleton
{
public:
static Singleton* Instance()
{
if( !pInstance )
{
if( destroyed )
{
// throw exception
}
else
{
Create();
}
}
return pInstance;
}
private:
static void Create()
{
static Singleton myInstance;
pInstance = &myInstance
}
Singleton() {}
Singleton( const Singleton& );
Singleton& operator=( const Singleton& );
~Singleton()
{
pInstance = 0;
detroyed = false;
}
static Singleton* pInstance;
static bool destroyed;
};
Singleton.cpp:
Singleton* Singleton::pInstance = 0;
bool Singleton::destroyed = false;
在我的主函数中:
Singleton* s = Singleton::Instance();
如果我将析构函数设置为public,则问题会消失。但是一本书(《现代C++设计》)说应该将其设置为private,以防止用户删除实例。实际上,我需要在析构函数中放置一些清理pInstance和destroyed的代码。
顺便说一下,我正在使用Visual C++ 6.0进行编译。
static Singleton * instance = new Singleton;
- 或者只是不使用单例模式并使用返回所需实例的自由函数。 - Georg Fritzsche