单例类模板
Posted 学习只为旅行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例类模板相关的知识,希望对你有一定的参考价值。
#include <iostream>
#include <string>
using namespace std;
class SObject
{
//静态成员变量必须在类外初始化!
static SObject* c_instance;
SObject(const SObject&);
SObject& operator= (const SObject&);
SObject()
{
}
public:
static SObject* GetInstance();
void print()
{
cout << "this = " << this << endl;
}
};
SObject* SObject::c_instance = NULL;
SObject* SObject::GetInstance()
{
if( c_instance == NULL )
{
c_instance = new SObject();
}
return c_instance;
}
int main()
{
SObject* s = SObject::GetInstance();
SObject* s1 = SObject::GetInstance();
SObject* s2 = SObject::GetInstance();
s->print();
s1->print();
s2->print();
return 0;
}
说明指向同一个对象
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
template
< typename T >
class Singleton
{
static T* c_instance;
public:
static T* GetInstance();
};
template
< typename T >
T* Singleton<T>::c_instance = NULL;
template
< typename T >
T* Singleton<T>::GetInstance()
{
if( c_instance == NULL )
{
c_instance = new T();
}
return c_instance;
}
#endif
#include <iostream>
#include <string>
#include "Singleton.h"
using namespace std;
class SObject
{
//友元概念
//Singleton这个类就可以访问SObject这个类所有成员了!!!
friend class Singleton<SObject>; // 当前类需要使用单例模式
//为什么要来一波友元的操作?
//SObject* s = new SObject();这么写直接报错!说明在外部无法定义类对象啊,构造函数私有,所以报错!
//那么声明友元后:SObject* s = Singleton<SObject>::GetInstance();
//其中,GetInstance()会new一个SObject的对象出来(此时调用私有的构造函数),本应该报错,但是友元的原因,Singleton这个类
//就可以访问SObject这个类所有成员了,不管构造函数私不私有,都不会报错!!!这里容易忘记之前的知识点!
SObject(const SObject&);
SObject& operator= (const SObject&);
SObject()
{
}
public:
void print()
{
cout << "this = " << this << endl;
}
};
int main()
{
SObject* s = Singleton<SObject>::GetInstance();
SObject* s1 = Singleton<SObject>::GetInstance();
SObject* s2 = Singleton<SObject>::GetInstance();
s->print();
s1->print();
s2->print();
return 0;
}
小结
以上是关于单例类模板的主要内容,如果未能解决你的问题,请参考以下文章