您的位置:首页 > 编程语言 > C语言/C++

单例模式的 模板方式实现 c++

2015-09-18 19:28 525 查看
</pre><pre>


// singleton.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "singleton.h"
int _tmain(int argc, _TCHAR* argv[])
{
	Msg::Instance().sayHello();
	return 0;
}


#ifndef SINGLETON_H
#define SINGLETON_H
#include <iostream>
template<class T>
class singleton
{
public:
	static T& Instance()
	{
	if(!pInstance)
	{
		pInstance = new T;
	}
	return *pInstance;
	}
private:
	singleton();
	static T* pInstance;
};
template<class T> T* singleton<T>::pInstance = NULL;
class msg{
public:
	void sayHello(){std::cout<<"hello"<<std::endl;};
};
typedef singleton<msg> Msg;
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: