STL list作为类的静态变量链接出错。该如何处理
STL list作为类的静态变量链接出错。代码如下:C/C++ code// stlTest.cpp : 定义控制台应用程序的入口点。//#
STL list作为类的静态变量链接出错。
代码如下:
C/C++ code// stlTest.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <list>using namespace std;struct Info{ int a; char str[255];};class DClass{ static list <Info> dList;public: static void ProInfo() { Info a; dList.push_back(a); }};int _tmain(int argc, _TCHAR* argv[]){ DClass the; the.ProInfo(); return 0;}
链接错误:
1>stlTest.obj : error LNK2001: unresolved external symbol "private: static class std::list<struct Info,class std::allocator<struct Info> > DClass::dList" (?dList@DClass@@0V?$list@UInfo@@V?$allocator@UInfo@@@std@@@std@@A)
1>E:\MyDocment\My Documents\Visual Studio 2005\Projects\stlTest\Debug\stlTest.exe : fatal error LNK1120: 1 unresolved externals
环境:
VS2005 Win32控制台
[解决办法]static 变量要单独定义呀.
在文件末尾加一句
static list <Info> DClass::dList;
[解决办法]int _tmain(int argc, _TCHAR* argv[])
{
DClass the;
the.ProInfo();
return 0;
}
静态变量使用之前需要定义的list<Info> DClass::dList(楼上正解)
静态函数调用不需要实体对象,DClass::ProInfo() ok?
[解决办法]#include "stdafx.h"
#include <list>
using namespace std;
struct Info
{
int a;
char str[255];
};
class DClass
{
static list <Info> dList;
public:
static void ProInfo()
{
Info a;
dList.push_back(a);
}
};
list<Info>DClass::dList;
int _tmain(int argc, _TCHAR* argv[])
{
DClass the;
the.ProInfo();
return 0;
}
我也学习了,静态变量声明,也要进定义
[解决办法]最根本的原因还是在于内存分配的原因,static变量分配在全局区,仅仅声明而不定义是不会分配内存的,所以无法解析