5

我正在尝试
map<string, int>
在我的程序中初始化一个静态映射,如下所示:

测试应用程序.h

class testApp(){
public:
void setup();
void update();
void renew();
static map<string, int> _someMap;
};

测试应用程序.cpp

testApp::setup(){
   _someMap["something"] = 1;
   _someMap["something2"] = 2;
cout<<_someMap["something"]<<"\n";
}

我不想使用boost这种短暂的 map 并为我的代码添加源依赖项。我不在C++11并且程序中没有构造函数,因为该类是某个框架的类。我在 Xcode 上并在执行上述操作时.cpp,出现以下错误:

Undefined symbols for architecture i386:
  "testApp::mapppp", referenced from:
      testApp::setup() in testApp.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

-->另外,假设我的地图是私有的,为此我在课堂上尝试过这样做:

...
private:
static someVariable;
static void someFunction();

.cpp

testApp::setup(){
someFunction();
}

错误:

Undefined symbols for architecture i386:
  "testApp::_someMap", referenced from:
      testApp::someFunction() in testApp.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
4

1 回答 1

5

您已经在类定义中声明了变量,但看起来您还没有定义它。每个静态变量都需要在一个翻译单元中定义。所以在你的源文件中添加一个定义:

map<string, int> testMap::_someMap;

如果您喜欢(并且如果您不能使用 C++11 初始化程序),您可以setup通过从函数结果初始化映射来避免调用函数:

map<string, int> make_map() {
    map<string, int> map;
    map["something"] = 1;
    map["something2"] = 2;
    return map;
}

map<string, int> testMap::_someMap = make_map();
于 2013-05-30T14:47:16.903 回答