已解决:http://pastebin.com/seEaALZh
我正在尝试创建简单的元素系统,我可以在其中通过其 ID 获取元素信息。我不能使用数组,因为项目 ID 可以说是随机的。我想使用声明的项目作为变量,我想通过它的 id 快速找到任何项目信息。我找到的唯一方法是 STL 映射。
所以我有这个简单的代码:
主要.h
#include <iostream> #include <map> enum { weapon, ammo }; class c_items { bool operator()(const c_items& l, const c_items& r) const { return (l.id < r.id); } public: c_items(void){}; c_items(int id, char name[], int type); char *name; int type; int id; }; extern std::map<int,c_items> Stuff; c_items::c_items(int id, char name[], int type) : id(id), type(type), name(name) { Stuff[id] = c_items(id, name, type); } const c_items brass_knuckles (546, "Brass knuckles", weapon), golf_club (2165, "Gold club", weapon);
main.cpp
#include "main.h" std::map<int,c_items> Stuff; using namespace std; int main() { // cout << Stuff[2165].name.data(); return 1; }
并且由于某种原因程序崩溃了。如何在类初始化时正确地将类数据插入到map中?
最佳答案
问题是初始化顺序。 brass_knuckles
和 golf_club
的静态构造函数首先运行,在 Stuff
的静态构造函数之前运行,因此它们尝试插入尚未插入的 map 构造。
此外,您绝不希望头文件中包含变量定义,因为如果您将头文件包含在多个源文件中,您最终会得到多个定义,这最多会导致链接失败。因此,您应该将定义移出 .h 文件并移至 .cpp 文件中。将它们放在 Stuff
的定义之后将解决初始化顺序问题。
如果你想在其他编译单元中使用它们,你可以在头文件中声明变量:
extern const c_items brass_knuckles, golf_club;
关于c++ - 如何在类初始化时将类插入到 STL 映射中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17634192/