1. 只支持单线程 (不推荐)

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Singleton
 5 {
 6 public:
 7     static Singleton* getInstance();//<1>必须是static,这样才可以通过类名访问。
 8 private:
 9     static Singleton* _instance;//<2>必须是static,这样生存期才是全局的。
10     Singleton();//<3>必须是private,这样就不能通过构造函数来实例化。
11 };
12 
13 Singleton* Singleton::getInstance()
14 {
15     if (_instance == NULL)
16     {
17         _instance = new Singleton();
18     }
19     return _instance;
20 }
21 Singleton* Singleton::_instance = NULL;//static变量必须初始化
22 Singleton::Singleton()    //构造函数既然要用到,而且类内部也声明了,就必须给出定义才能用。
23 {
24     cout << "success" << endl;
25 }
26 
27 int main()
28 {
29     Singleton* sgt = Singleton::getInstance();
30 }
View Code

相关文章:

  • 2021-09-06
  • 2022-12-23
  • 2021-11-30
  • 2021-09-19
  • 2021-09-30
  • 2021-08-08
猜你喜欢
  • 2022-01-20
  • 2021-08-26
  • 2022-03-08
  • 2022-12-23
  • 2022-12-23
  • 2021-06-11
  • 2022-12-23
相关资源
相似解决方案