【问题标题】:Weird linker error with static std::map静态 std::map 的奇怪链接器错误
【发布时间】:2011-04-04 20:17:40
【问题描述】:

当我尝试在 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

【问题讨论】:

标签: c++ static map std


【解决方案1】:

您已经声明了静态成员_myMap,但没有定义它。在int main()上方添加这一行:

std::map<int, int> MyClass::_myMap;

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

【讨论】:

  • 如果我有另一个静态变量也需要这个,例如std::string myString ?
  • 我认为您的意思不是“但未定义它”,而是“但未初始化它”
  • 2019,而且那个错误仍然没有在 Visual Studio 中提示更具体的错误信息...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多