2010-08-27 130 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