2010-08-27 117 views
20

为什么我收到链接错误,当我尝试在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" ([email protected]@@[email protected][email protected]@[email protected]@[email protected][email protected][email protected]@@@[email protected]@[email protected]@A) test22.obj test22 
+1

本质上是[静态结构链接器错误](http://stackoverflow.com/questions/1850809/static-struct-linker-error)等的重复。 – Troubadour 2010-08-27 14:27:42

+0

[定义静态成员在C++中]的可能的重复(http://stackoverflow.com/questions/3536372/defining-static-members-in-c) – 2012-09-25 03:57:33

回答

26

声明了静态成员_myMap,但没有定义它。加入这一行的正上方int main():它

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

这样认为已经宣布,但在任何.cpp文件中没有定义的功能 - 如果你使用它,你得到一个连接错误。

+0

这也是需要的,如果我有另一个静态变量,例如std :: string myString? – BlaBla 2010-08-27 14:29:47

+0

@BlaBla:是的...... – 2010-08-27 14:30:58

+0

我想你不是指“但没有定义它”,而是“但没有初始化它” – sergiol 2015-06-25 10:53:20