class Singleton
{
public:
Singleton()
{
if (_count == 0)
{
cout << "进行构造函数" << endl;
_count++;
}
else
{
cout << "构造失败" << endl;
}
}
private:
static int _count;
};
int Singleton::_count=0;
void test()
{
Singleton t1;
Singleton t2;
}
int main()
{
test();
system("pause");
return 0;
}
class Singleton
{
public:
static Singleton* GetConstuct()
{
if (instance == NULL)
{
instance = new Singleton();
return instance;
}
return NULL;
}
private:
static Singleton* instance;
Singleton()
{
cout << "进行构造函数" << endl;
}
};
Singleton* Singleton::instance = NULL;
void test()
{
Singleton* t1 = Singleton::GetConstuct();
Singleton* t2= Singleton::GetConstuct();
}
int main()
{
test();
system("pause");
return 0;
}
利用静态构造函数,初始化静态变量的时候创建实例
class Singleton
{
public:
static Singleton* GetConstuct()
{
return instance;
}
private:
Singleton()
{
cout << "进行构造函数" << endl;
}
static Singleton* instance;
};
Singleton* Singleton::instance = new Singleton();
void test()
{
Singleton* t1 = Singleton::GetConstuct();
Singleton* t2 = Singleton::GetConstuct();
}
int main()
{
test();
system("pause");
return 0;
}