单例类模板

荒凉一梦 提交于 2020-02-10 01:06:49
单例类模板程序
Singleton.h
#ifndef _SINGLETLON_H_
#define __SINGLETLON_H_
template <typename T>
class singletlon
{
  static T* Instance;
public:
  static T* Get_Instance();
};
template <typename T>
T* singletlon<T>:: Instance = NULL;
template <typename T>
T* singletlon<T>::Get_Instance()
{
  if (Instance == NULL)
  {
     Instance = new T();
               
  }
  return Instance;
}
#endif
main.cpp
#include <iostream>
#include <string>
#include "Singletlon.h"
using namespace std;
class SObject
{
    friend class singletlon<SObject>;
    SObject()
    {
    }
    SObject(const SObject& obj);
    SObject& operator = (const SObject& obj);
public:
    void print();
};
void SObject::print()
{
    cout << "this=" << this << endl;
}
int main()
{
    SObject* s1 = singletlon<SObject>:: Get_Instance();
    SObject* s2 = singletlon<SObject>::Get_Instance();
    SObject* s3 = singletlon<SObject>::Get_Instance();
    s1->print();
    s2->print();
    s2->print();
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!