静态std :: map出现奇怪的链接器错误

Bla*_*Bla 23 c++ static 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);

}
Run Code Online (Sandbox Code Playgroud)

错误是:

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
Run Code Online (Sandbox Code Playgroud)

Ash*_*ain 30

您已声明静态成员_myMap,但未定义它.在上面添加此行int main():

std::map<int, int> MyClass::_myMap;
Run Code Online (Sandbox Code Playgroud)

可以把它想象成一个已声明但未在任何.cpp文件中定义的函数 - 如果使用它会出现链接器错误.

  • 2019 年,该错误仍然没有在 Visual Studio 中提示更具体的错误消息... (2认同)