如果在一个函数中声明并初始化一个变量后,再次调用时,并不会再次初始化
void func()
{
static int b = 0;
if (b == 0){
cout << "b is zero" << endl;
}
else{
cout << "b is not a zero " <<endl;
}
b++;
}
连续两次调用func(); 输出的是不同的结果
一次b是0,一个b是1;
这个可以用在单例模式中
template<class T>
class singleton
{
public:
static T* &Instance()
{
static T* pInstance = NULL;
if (pInstance==NULL)
{
pInstance = new T();
}
return pInstance;
}
private:
singleton();
};
class msg{
public:
void sayHello(){ cout << "hello" << endl; }
};
#define DEFINE_SINGLETION_TYPE(impl,g) typedef singleton<impl> g;
int _tmain(int argc, _TCHAR* argv[])
{
//Msg是一个类
DEFINE_SINGLETION_TYPE(msg, Msg);
//调用静态工厂方法
Msg::Instance()->sayHello();
return 0;
}