静态映射初始化 [英] static map initialization

查看:113
本文介绍了静态映射初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:我有以下代码:

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

如何对任何case初始化(静态)opMap _?

How can I any case initialize (static) opMap_?

推荐答案

如果你使用C ++ 11,你可以使用初始化列表:

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 }
}; 

如果您无法访问支持C ++ 11标准的编译器,请执行以下操作:

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();

这篇关于静态映射初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆