static map initialization

2019-03-23 07:46发布

I have the following code :I have the following code:

//MyClass.h
class MyClass {
public:
      typedef std::map<std::string, int> OpMap;
      static OpMap opMap_;


     //methods
};

//MyClass.cpp
//Init opMap_
MyClass::opMap_["x"] = 1; //compilation error

How can I any case initialize (static) opMap_?

标签: c++ map static
2条回答
男人必须洒脱
2楼-- · 2019-03-23 08:19

As you are using VS2010, you need to initialize your static member in MyClass.cpp, in front of any other member function definitions. call MyClass::InitMap() if you want to initialize opMap_.

MyClass.h

class MyClass
{
public:
  MyClass(void);
  ~MyClass(void);
public:
   typedef std::map<std::string, int> OpMap;
   static OpMap opMap_;    
   static void InitMap();
};

MyClass.cpp

std::map<std::string, int> MyClass::opMap_;
MyClass::MyClass(void)
{
   InitMap(); // just sample if you want to initialize opMap_ inside MyClass constructor
}

void InitMap()
{
  MyClass::opMap_["x"] = 1;
}
查看更多
萌系小妹纸
3楼-- · 2019-03-23 08:24

If you're using C++11, you could use initializer lists:

//MyClass.h
class MyClass {
public:
      typedef std::map<std::string, int> OpMap;
      static OpMap opMap_;
};

//MyClass.cpp
MyClass::OpMap MyClass::opMap_ = { 
    { "x", 1 }
}; 

If you don't have access to a compiler that supports the C++11 standard, you could do the following:

//MyClass.h
class MyClass {
public:
      typedef std::map<std::string, int> OpMap;
      static OpMap opMap_;
private:
      static OpMap init_map() {
          OpMap some_map;
          some_map["x"] = 1;
          return some_map;
      }
};

//MyClass.cpp
MyClass::OpMap MyClass::opMap_ = init_map();
查看更多
登录 后发表回答