首页 > 编程 > C++ > 正文

c++函数中的static

2019-11-08 18:43:28
字体:
来源:转载
供稿:网友

如果在一个函数中声明并初始化一个变量后,再次调用时,并不会再次初始化

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;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选