C++ 静态地图初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13464325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
static map initialization
提问by Yakov
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_?
我如何在任何情况下初始化(静态)opMap_?
回答by mfontanini
If you're using C++11, you could use initializer lists:
如果您使用的是 C++11,则可以使用初始化列表:
//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:
如果您无权访问支持 C++11 标准的编译器,您可以执行以下操作:
//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();
回答by billz
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_
.
当您使用 VS2010 时,您需要在 MyClass.cpp 中初始化您的静态成员,在任何其他成员函数定义之前。MyClass::InitMap()
如果要初始化,请致电opMap_
。
MyClass.h
我的类.h
class MyClass
{
public:
MyClass(void);
~MyClass(void);
public:
typedef std::map<std::string, int> OpMap;
static OpMap opMap_;
static void InitMap();
};
MyClass.cpp
我的类.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;
}