#include
class CSingleton
{
private:
CSingleton() // 构造函数是私有的
{
}
static CSingleton *m_pInstance;
public:
void output()
{
std::cout << "ghj&gjjvghff" << std::endl;
}
static CSingleton *GetInstance()
{
if (m_pInstance == NULL) // 判断是否第一次调用
m_pInstance = new CSingleton();
return m_pInstance;
}
};
int main()
{
CSingleton *p=CSingleton::GetInstance();
p->output();
return 0;
}
CSingleton类是网上找的,编译一致不能通过,提示如图
构造函数得是public的
在全局区加一句
CSingleton* CSingleton::m_pInstance=NULL;
静态数据成员是静态存储的,它是静态生存期,必须对它进行初始化。
static CSingleton *m_pInstance = NULL;
在cpp文件夹中定义它static CSingleton *m_pInstance;
m_pInstance没有初始化,应该在声明时初始化为NULL
m_pInstance应该初始化为NULL,static CSingleton *m_pInstance = NULL;静态成员变量在生成对象前就加载,必须对它进行初始化
没有初始化的问题, 直接在cpp类的外面,定义一下static CSingleton:: m_pInstance = NULL,静态变量属于类但不属于特定对象,存储在全局区,编译时候靠前,就像你声明一个类方法,但是不实现一样的问题。编译的时候看到这个类型会去找这个类型的定义。找不到定义肯定报链接错误了。