搞了一个通宵了,百度过很多资料,始终解决不了这个问题。令我开始对C++的繁琐感到厌倦了。为了编译通过这么一个小问题,折腾这么长时间,真心觉得这种语言繁琐,刻板,效率低,过时了,让我这个6年的C++粉开始有点失望……
- #ifndef __SINGLETON__H__
- #define __SINGLETON__H__
-
- template <typename T>
- class Singleton
- {
- public:
-
- static T* GetInstance()
- {
- return m_pInstance;
- }
-
-
- protected:
-
- Singleton() {}
- ~Singleton() {}
-
-
- private:
-
- Singleton(const Singleton<T> &);
- Singleton& operator = (const Singleton<T> &);
-
- static T* m_pInstance;
-
- class Worker // 这里在类模板中定义了一个内部类
- {
- public:
-
- Worker()
- {
- i = 0;
- if ( !m_pInstance )
- {m_pInstance = new T();printf("ccc\n");}
-
- }
-
- ~Worker()
- {
-
- if ( m_pInstance )
- {delete m_pInstance;printf("ddd\n");}
-
- }
- int i;
- };
-
- static Worker worker; // 静态内部类成员,私有的。为了在类模板实例创建时自动调用此静态内部类的构造函数,销毁时自动调用此静态内部类的析构函数
- };
-
- template <typename T> T* Singleton<T>::m_pInstance = NULL; // 这句编译通过
- template <typename T> Singleton<T>::Worker Singleton<T>::worker; // 就是这句编译不通过,纠结了一晚上了,浪费了许多时间,不知道该怎么写,求大神们指教。
-
- #define SINGLETON_INIT(Type) friend Type* Singleton<Type>::GetInstance(); private: Type(); ~Type()
-
- #endif
错误输出:
警告 1 warning C4346: “Singleton::Worker”: 依赖名称不是类型
错误 2 error C2143: 语法错误 : 缺少“;”(在“Singleton::worker”的前面)
错误 3 error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int