读书人

Singleton方式c++模板实现出错

发布时间: 2013-01-05 15:20:39 作者: rapoo

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;
};


main.cpp

#include "Singleton.h"

int main()
{

Singleton<Point> pt;
Point* pt1 = pt.getSingletonPtr();
pt1->setMember(5,3);
pt1->outPut();


while (1)
{
}
}

出错:
1>main.cpp
1>d:\program files\microsoft visual studio\myprojects\singleton_test\main.cpp(8) : error C2248: “Singleton<T>::Singleton”: 无法访问 protected 成员(在“Singleton<T>”类中声明)
1> with
1> [
1> T=Point
1> ]
1> d:\program files\microsoft visual studio\myprojects\singleton_test\singleton.h(29) : 参见“Singleton<T>::Singleton”的声明
1> with
1> [
1> T=Point
1> ]
1>d:\program files\microsoft visual studio\myprojects\singleton_test\main.cpp(8) : error C2248: “Singleton<T>::~Singleton”: 无法访问 protected 成员(在“Singleton<T>”类中声明)
1> with
1> [
1> T=Point
1> ]
1> d:\program files\microsoft visual studio\myprojects\singleton_test\singleton.h(30) : 参见“Singleton<T>::~Singleton”的声明
1> with
1> [
1> T=Point
1> ]
1>生成日志保存在“file://d:\Program Files\Microsoft Visual Studio\MyProjects\Singleton_Test\Debug\BuildLog.htm”
1>Singleton_Test - 2 个错误,0 个警告
========== 生成: 0 已成功, 1 已失败, 0 最新, 0 已跳过 ==========

请指教
[解决办法]
此时你的Point类是singleton吗, 明显不是, 一般可以这么定义:

// Singleton base class, each class need to be a singleton should


// 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();

读书人网 >软件开发

热点推荐