首页 > 代码库 > 单实例

单实例

singleTon.h

 1 #pragma once
 2 class SingleTon
 3 {
 4 public:
 5     
 6     ~SingleTon(void);
 7     static SingleTon* getInstance();
 8 
 9 private:
10     SingleTon(void);
11     static SingleTon* Instance;
12 
13 public:
14     void SetNum(int num);
15     void GetNum(void);
16 private:
17     int Num;
18 
19 };

SingleTon.cpp

 1 #include <iostream>
 2 
 3 #include "SingleTon.h"
 4 
 5 SingleTon* SingleTon::Instance = NULL;//累指针初始化赋值
 6 
 7 SingleTon::SingleTon(void)
 8 {
 9     Num = 0;
10 }
11 
12 
13 SingleTon::~SingleTon(void)
14 {
15     if(Instance != NULL)
16     {
17         delete Instance;
18         Instance = NULL;
19     }
20    Num = 0;
21 }
22 
23 SingleTon* SingleTon::getInstance()
24 {
25     if(Instance == NULL)
26     {
27         Instance = new SingleTon;
28     }
29     return Instance;
30 }
31 
32 void SingleTon::SetNum(int num)
33 {
34     Num = num;
35 }
36 
37 void SingleTon::GetNum()
38 {
39     std::cout<<"Num = "<<Num<<std::endl;
40 }

 

单实例