模板类构造函数与析构函数无法访问私有成员(明明就是公有的)
写成这样:
#ifndef __SINGLETON__H__
#define __SINGLETON__H__
template <typename T>
class Worker;
template <typename T>
class Singleton
{
friend class Worker<T>;
public:
static T* GetInstance()
{
worker.i=3;
/*worker.m_pInstance = new T();
return worker.m_pInstance;*/
}
public:
Singleton() {}
~Singleton() {}
public:
/*Singleton(const Singleton<T> &);
Singleton& operator = (const Singleton<T> &);*/
static Worker<T> worker;
};
template <typename T>
class Worker
{
friend class Singleton<T>;
public:
Worker()
{
i = 0;
if ( !m_pInstance )
{m_pInstance = new T();printf("ccc\n");} // 出错行在这里
}
~Worker()
{if ( m_pInstance )
{delete m_pInstance;printf("ddd\n");} // 出错行在这里
}
public:
int i;
T* m_pInstance;
};
//template <typename T> T* Singleton<T>::m_pInstance = NULL;
template <typename T> typename Worker<T> Singleton<T>::worker;
#define SINGLETON_INIT(Type) friend Type* Singleton<Type>::GetInstance(); private: Type(); ~Type()
#endif
或者是这样,都不行,编译结果一模一样:
#ifndef __SINGLETON__H__
#define __SINGLETON__H__
template <typename T>
class Worker;
template <typename T>
class Singleton
{
friend class Worker<T>;
public:
static T* GetInstance()
{
worker.i=3;
/*worker.m_pInstance = new T();
return worker.m_pInstance;*/
}
public:
Singleton() {}
~Singleton() {}
public:
/*Singleton(const Singleton<T> &);
Singleton& operator = (const Singleton<T> &);*/
static T* m_pInstance;
static Worker<T> worker;
};
template <typename T>
class Worker
{
friend class Singleton<T>;
public:
Worker()
{
i = 0;
if ( !Singleton<T>::m_pInstance )
{Singleton<T>::m_pInstance = new T();printf("ccc\n");} // 出错行在这里
}
~Worker()
{if ( Singleton<T>::m_pInstance )
{delete Singleton<T>::m_pInstance;printf("ddd\n");} // 出错行在这里
}
public:
int i;
};
template <typename T> T* Singleton<T>::m_pInstance = NULL;
template <typename T> typename Worker<T> Singleton<T>::worker;
#define SINGLETON_INIT(Type) friend Type* Singleton<Type>::GetInstance(); private: Type(); ~Type()
#endif
编译结果:
A::A”: 无法访问 private 成员(在“A”类中声明)