0

对于以下代码,我收到链接器错误。我想知道如何初始化stl map

#include <iostream>
#include <map>
#include <string>

class Test {
public:
  Test() {
  }
  static void setSerializer(void* fnptr, std::string className) {
    m_registry.insert(std::make_pair(className, fnptr));
  }
  static void* getSerializer(std::string className) {
    return m_registry.find(className)->second;
  }
private:
  static std::map<std::string, void*> m_registry;
};

void fn() {
}

int main() {
  Test::setSerializer(&fn,"abc");
  return 0;
}
4

2 回答 2

3

您需要在类实现中定义静态变量——就像对外部C++ 变量所做的那样。仅仅在课堂上声明是不够的!为此,请将以下代码放入 .cpp 文件中:

std::map<std::string, void*> Test::m_registry;
于 2012-11-16T07:02:49.173 回答
2

您需要在 .cpp 文件中初始化静态成员。通常我们在 .h 文件中声明类并将定义放入 .cpp 文件中。我对您的代码做了一些增强,如下所示:

测试.h

class Test 
{
public:
  Test() { }
  static void setSerializer(std::string className, void* fnptr); // I swap the order of parameter. it makes more sense to have name and pointer pair
  static void* getSerializer(std::string className);

private:
  static std::map<std::string, void*> m_registry;
};

测试.cpp

std::map<std::string, void*> Test::m_registry;   // initialize static member here

void Test::setSerializer(std::string className, void* fnptr)
{
  m_registry.insert(std::make_pair(className, fnptr));
}

void* Test::getSerializer(std::string className) {    
  auto iter =  m_registry.find(className);   // check if iterator is valid 
  if (iter != m_registry.end() )
  {
    return (*iter).second;
  }
  return NULL;
}
于 2012-11-16T07:14:03.383 回答