C++ 将静态私有映射初始化为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11247407/
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
Initialize a static private map as empty
提问by Nikolai Fetissov
I have a static map
that is a private
data member. How do I initialize it in the implementation file so that it's initial containers are empty? It is not const
. It is important that nothing is in this container at start.
我有一个static map
这是一个private
数据成员。如何在实现文件中初始化它,使其初始容器为空?不是const
。开始时此容器中没有任何内容很重要。
回答by Nikolai Fetissov
Header:
标题:
class XXX {
private:
static std::map<X,Y> the_map; // declares static member
// ...
Implementation file:
实现文件:
std::map<X,Y> XXX::the_map; // defines static member
That will insert a constructor call for your map into your program initialization code (and a destructor into the cleanup). Be careful though - the order of static constructors like this between different translation units is undefined.
这会将映射的构造函数调用插入到程序初始化代码中(并在清理中插入析构函数)。不过要小心——像这样的静态构造函数在不同翻译单元之间的顺序是未定义的。
回答by Linuxios
How about this (if I understand you correctly):
这个怎么样(如果我理解正确的话):
std::map<T,T2> YourClass::YourMember = std::map<T,T2>();
回答by Black
If You define it in the class definition, then You have to declare it in the implementation:
如果您在类定义中定义它,那么您必须在实现中声明它:
--- test.h ---
--- test.h ---
// includes and stuff...
class SomeClass
{
private:
static std::map<int,std::string> myMap;
};
--- test.cpp ---
--- test.cpp ---
std::map<int,std::string> SomeClass::myMap; // <-- initialize with the map's default c'tor
You can use a initialization, too:
您也可以使用初始化:
std::map<int,std::string> SomeClass::myMap = std::map<int,std::string>(myComparator);