[请教] 请高手帮忙解答一下自己写的类模板和单例小例子遇到的编译问题,谢谢了

2017-12-27 09:31:54 +08:00
 jimy1

照着例子写的,例子里面是分文件写的,因为编译出错我把几个文件的代码汇总到 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;
}
2000 次点击
所在节点    C
3 条回复
GeruzoniAnsasu
2017-12-27 09:39:31 +08:00
类 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;//类外定义并初始化
linux40
2017-12-27 09:40:23 +08:00
就是 static member 声明了没定义。
gnaggnoyil
2017-12-27 09:47:42 +08:00
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.

```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/417900

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX