class singleton { public: static singleton* instance(); //声明一个静态成员函数 protect: singleton(); private: static singleton* _instance; //声明一个静态成员变量 }; singleton* singleton::_instance = 0; singleton* singleton::instance() { if( _instance == 0 ) _instance = singleton(); return _instance; } singleton::singleton() { cout<<"singleton"<<endl; } int main() { singleton* sgn = singleton::instance(); return 0; }
类中定义的静态成员变量在类外要初始化