以下代码适用于Visual C++ 2008,但在Visual C++ 6中出现以下错误。请问为什么会出错,我该如何解决这个问题并使析构函数仍处于私有状态?
class X
{
public:
static X& instance()
{
static X database;
return database;
}
private:
X() {} // Private constructor
~X() {} // Private destructor
X(const X&); // Prevent copy-construction
X& operator=(const X&); // Prevent assignment
};
int main()
{
X::instance();
}
C:\Projects\ttt6\main.cpp(178) : error C2248: 'X::~X' : 无法访问已在类“X”中声明的私有成员 C:\Projects\ttt6\main.cpp(175) : 参见“X::~X”的声明
protected
。对于单例模式,你希望只有类的静态CreateInstance()
方法才能创建一个实例,因此需要将构造函数设置为private
。 - Scott Smith