我的应用程序中有一些静态unordered_maps,我希望能够在启动时初始化。他们不是班级的一部分。在我的初始设置中,标头和源文件如下:
namespace Game
{
namespace Elements
{
enum Element
{
Air = 1,
Dark = 2,
Earth = 4,
Elementless = 8,
Fire = 16,
Ice = 32,
Light = 64,
SpaceTime = 128,
Thunder = 256,
Water = 512,
};
static boost::unordered_map<Element, std::string> ElementNameMap;
static boost::unordered_map<std::string, Element> NameElementMap
}
}
源文件:
#include "Elements.h"
using namespace std;
using namespace Game::Elements;
boost::unordered_map<Element, std::string> ElementNameMap = boost::assign::map_list_of
(Element::Air, string("Air"))
(Element::Dark, string("Dark"))
(Element::Earth, string("Earth"))
(Element::Elementless, string("Elementless"))
(Element::Fire, string("Fire"))
(Element::Ice, string("Ice"))
(Element::Light, string("Light"))
(Element::SpaceTime, string("SpaceTime"))
(Element::Thunder, string("Thunder"))
(Element::Water, string("Water"))
;
boost::unordered_map<std::string, Element> NameElementMap = boost::assign::map_list_of
(string("Air"), Element::Air)
(string("Dark"), Element::Dark)
(string("Earth"), Element::Earth)
(string("Elementless"), Element::Elementless)
(string("Fire"), Element::Fire)
(string("Ice"), Element::Ice)
(string("Light"), Element::Light)
(string("SpaceTime"), Element::SpaceTime)
(string("Thunder"), Element::Thunder)
(string("Water"), Element::Water)
;
然而,每当我尝试这样做,然后尝试在地图上进行查找(即Game :: Elements :: NameElementMap [std :: string(“Air”)])它总是返回一个空字符串,并且大小在那个使用上下文是0。
我尝试将初始化移动到头文件中(即在头文件中放置
static boost::unordered_map<Element, std::string> ElementNameMap = boost::assign::map_list_of
(Element::Air, string("Air"))
(Element::Dark, string("Dark"))
(Element::Earth, string("Earth"))
(Element::Elementless, string("Elementless"))
(Element::Fire, string("Fire"))
(Element::Ice, string("Ice"))
(Element::Light, string("Light"))
(Element::SpaceTime, string("SpaceTime"))
(Element::Thunder, string("Thunder"))
(Element::Water, string("Water"))
;
static boost::unordered_map<std::string, Element> NameElementMap = boost::assign::map_list_of
(string("Air"), Element::Air)
(string("Dark"), Element::Dark)
(string("Earth"), Element::Earth)
(string("Elementless"), Element::Elementless)
(string("Fire"), Element::Fire)
(string("Ice"), Element::Ice)
(string("Light"), Element::Light)
(string("SpaceTime"), Element::SpaceTime)
(string("Thunder"), Element::Thunder)
(string("Water"), Element::Water)
;
但编译器然后抱怨没有默认构造函数。我做错了什么?
提前致谢
答案 0 :(得分:2)
您必须将定义放在正确的命名空间中。否则,您将在全局命名空间中定义两个新映射,而不是Game::Elements
中的映射:
namespace Game {
namespace Elements {
boost::unordered_map<Element, std::string> ElementNameMap = boost::assign::map_list_of
(Air, string("Air"))
(Dark, string("Dark"))
...
}
}
(此外,枚举不会创建新的命名空间,因此它只是Air
,而不是Element::Air
。)