奇怪的链接错误::地图
问题描述:
为什么我收到链接错误,当我尝试在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
答
声明了静态成员_myMap
,但没有定义它。加入这一行的正上方int main()
:它
std::map<int, int> MyClass::_myMap;
这样认为已经宣布,但在任何.cpp文件中没有定义的功能 - 如果你使用它,你得到一个连接错误。
本质上是[静态结构链接器错误](http://stackoverflow.com/questions/1850809/static-struct-linker-error)等的重复。 – Troubadour 2010-08-27 14:27:42
[定义静态成员在C++中]的可能的重复(http://stackoverflow.com/questions/3536372/defining-static-members-in-c) – 2012-09-25 03:57:33