c++单例

内:

#include <iostream>

class Singleton
{
public:
    static Singleton *GetInstance()
    {
        return m_pSingletom;
    }
    
    int function() {
        return 0;
    }
private:
    static Singleton *m_pSingletom;
    // 构造私有函数
    Singleton()
    {
        if (m_pSingletom == NULL) {
            m_pSingletom = new Singleton();
        }
    }
};

Singleton *Singleton::m_pSingletom = 0;

int main(int argc, const char * argv[])
{
    Singleton *single = Singleton::GetInstance();
    int n = single->function();
    
    printf("%d
",n);
    std::cout << "Hello, World!
";
    return 0;
}

.h

#ifndef __SingletonDemo__Test__
#define __SingletonDemo__Test__

#include <iostream>

class Singleton
{
public:
    static Singleton *GetInstance();
    int function();
private:
    static Singleton *m_pSingleton;
};

#endif /* defined(__SingletonDemo__Test__) */
.cpp

#include "Test.h"

Singleton *Singleton::m_pSingleton = NULL;

Singleton *Singleton::GetInstance(){
    if (Singleton::m_pSingleton == NULL) {
        Singleton::m_pSingleton = new Singleton();
    }
    
    return m_pSingleton;
}

int Singleton::function()
{
    return 9;
}
原文地址:https://www.cnblogs.com/lihaibo-Leao/p/3955453.html