C++实现单例模式
单例模式:只能生成一个实例的类即是实现了Singleton模式的类型。
#include <iostream> using namespace std; class singleton { public : static singleton* getInstance(); private: singleton(); static singleton* instance; static int num; }; int singleton::num = 0; singleton* singleton::instance = nullptr; singleton::singleton() { num++; cout << num <<"singleton is created!" << endl; } singleton* singleton::getInstance() { if(instance == nullptr) { instance = new singleton; } return instance; } int main() { singleton* instance = singleton::getInstance(); return 0; }