照着例子写的,例子里面是分文件写的,因为编译出错我把几个文件的代码汇总到 main.cpp ,注释了一些类成员变量,单例的代码没有改动,报错的信息如下,请高手帮忙解答一下,谢谢了。
[jimy@M610-252126 f]$ g++ -m64 -g -Wall main.cpp
/tmp/ccfyJPP4.o: In function `CSingleton<CGlobalMgr>::instance()':
/home/jimy/f/main.cpp:10: undefined reference to `CSingleton<CGlobalMgr>::m_slInstance'
collect2: ld returned 1 exit status
代码:
#include <iostream>
using std::cout;
using std::endl;
template<class TYPE>
class CSingleton {
public:
static TYPE *instance() {
return &m_slInstance;
};
public:
CSingleton() {
}
virtual ~CSingleton() {
}
private:
static TYPE m_slInstance;
};
class CGlobalMgr {
public:
CGlobalMgr() {
m_gmSafeExitFlag = false;
m_gmRefreshFlag = false;
}
virtual ~CGlobalMgr() {
}
public:
bool init(){
cout<<"OK"<<endl;
return true;
}
private:
bool m_gmSafeExitFlag;
bool m_gmRefreshFlag;
};
typedef CSingleton<CGlobalMgr> GLOBALMGR_S;
#define GLOBALMGR() GLOBALMGR_S::instance()
int main(int argc, char *argv[]){
if(!GLOBALMGR()->init()) {
return 0;
}
return 0;
}
1
GeruzoniAnsasu 2017-12-27 09:39:31 +08:00 1
类 static 成员变量除了要在类内声明,还要在类外定义,但 template 又要求声明和实现都必须放在一起
template<class TYPE> class CSingleton { public: static TYPE *instance() { return &m_slInstance; }; public: CSingleton() { } virtual ~CSingleton() { } private: static TYPE m_slInstance; }; template<class TYPE> TYPE CSingleton<TYPE>::m_slInstance = nullptr;//类外定义并初始化 |
2
linux40 2017-12-27 09:40:23 +08:00 via Android 1
就是 static member 声明了没定义。
|
3
gnaggnoyil 2017-12-27 09:47:42 +08:00 3
http://eel.is/c++draft/class.static.data#2
``` The declaration of a non-inline static data member in its class definition is not a definition and may be of an incomplete type other than cv void. The definition for a static data member that is not defined inline in the class definition shall appear in a namespace scope enclosing the member's class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator. ``` |