Singleton模式c++模板实现,出错
Singleton.h文件
#include "iostream"
using namespace std;
// Singleton模板类
template <class T>
class Singleton
{
public:
static inline T* getSingletonPtr()
{
if ( NULL == mSingletonPtr)
{
mSingletonPtr = new T;
}
else
{
cout << "Thie Single already exist!" << endl;
}
return mSingletonPtr;
}
protected:
Singleton() {}
~Singleton() {}
static T* mSingletonPtr;
};
// 测试类
class Point
{
public:
Point(){}
~Point() {}
void inline outPut()
{
cout << x << y << endl;
}
void inline setMember(int x,int y)
{
this->x = x;
this->y = y;
}
protected:
private:
int x,y;
};
#include "Singleton.h"
int main()
{
Singleton<Point> pt;
Point* pt1 = pt.getSingletonPtr();
pt1->setMember(5,3);
pt1->outPut();
while (1)
{
}
}
// derived from this class
template <class T> class Singleton
{
protected:
Singleton(){}
public:
static T& Instance()
{
static T instance;
return instance;
}
};
// Concrete singleton class, derived from Singleton<T>
class ExampleSingleton: public Singleton<ExampleSingleton>
{
// so that Singleton<ExampleSingleton> can access the
// protected constructor
friend class Singleton<ExampleSingleton>;
protected:
ExampleSingleton(){}
public:
// This class's real functionalities
void Write(){printf("Hello, World!");}
};
// use this singleton class
ExampleSingleton::Instance().Write();