静态 std::map 出现奇怪的链接器错误
当我尝试在 Visual Studio 2008 中编译此
#include <stdafx.h>
#include <iostream>
#include <map>
#include <string>
class MyClass
{
public:
MyClass () { };
virtual ~MyClass() {};
static std::string niceString (std::map<int, int> mappp) { _myMap = mappp; return "nice string"; };
private:
static std::map<int, int> getMap ( ) { return _myMap; };
static std::map<int, int> _myMap;
};
int main(){
std::map<int, int> mappp;
mappp[1] = 1;
std::cout << MyClass::niceString(mappp);
}
错误时,为什么会出现链接器错误:
Error 1 error LNK2001: unresolved external symbol "private: static class std::map<int,int,struct std::less<int>,class std::allocator<struct std::pair<int const ,int> > > MyClass::_myMap" (?_myMap@MyClass@@0V?$map@HHU?$less@H@std@@V?$allocator@U?$pair@$$CBHH@std@@@2@@std@@A) test22.obj test22
Why do I get linker error when I try to compile this in Visual Studio 2008
#include <stdafx.h>
#include <iostream>
#include <map>
#include <string>
class MyClass
{
public:
MyClass () { };
virtual ~MyClass() {};
static std::string niceString (std::map<int, int> mappp) { _myMap = mappp; return "nice string"; };
private:
static std::map<int, int> getMap ( ) { return _myMap; };
static std::map<int, int> _myMap;
};
int main(){
std::map<int, int> mappp;
mappp[1] = 1;
std::cout << MyClass::niceString(mappp);
}
error is:
Error 1 error LNK2001: unresolved external symbol "private: static class std::map<int,int,struct std::less<int>,class std::allocator<struct std::pair<int const ,int> > > MyClass::_myMap" (?_myMap@MyClass@@0V?$map@HHU?$less@H@std@@V?$allocator@U?$pair@$CBHH@std@@@2@@std@@A) test22.obj test22
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已声明静态成员
_myMap
,但未定义它。在int main()
上方添加此行:将其视为已在任何 .cpp 文件中声明但未定义的函数 - 如果使用它,您会收到链接器错误。
You've declared the static member
_myMap
, but not defined it. Add this line just aboveint main()
:Think of it like a function that has been declared but not defined in any .cpp file - you get a linker error if you use it.