c++ - 如何在类初始化时将类插入到 STL 映射中

标签 c++ class dictionary constructor initialization

已解决:http://pastebin.com/seEaALZh

我正在尝试创建简单的元素系统,我可以在其中通过其 ID 获取元素信息。我不能使用数组,因为项目 ID 可以说是随机的。我想使用声明的项目作为变量,我想通过它的 id 快速找到任何项目信息。我找到的唯一方法是 STL 映射。

所以我有这个简单的代码:

  1. 主要.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);
    
  2. 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_knucklesgolf_club 的静态构造函数首先运行,在 Stuff 的静态构造函数之前运行,因此它们尝试插入尚未插入的 map 构造。

此外,您绝不希望头文件中包含变量定义,因为如果您将头文件包含在多个源文件中,您最终会得到多个定义,这最多会导致链接失败。因此,您应该将定义移出 .h 文件并移至 .cpp 文件中。将它们放在 Stuff 的定义之后将解决初始化顺序问题。

如果你想在其他编译单元中使用它们,你可以在头文件中声明变量:

extern const c_items brass_knuckles, golf_club;

关于c++ - 如何在类初始化时将类插入到 STL 映射中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17634192/

相关文章:

c++ - 从 Lua 内部获取 Lua 状态,以便它可以传递回 C

c++ - Waf 生成 Visual Studio 项目?

class - 我无法从 Kotlin 的嵌套类中联系到任何类成员

ios - 如何检查 connectionDidFinishLoading 何时完成

python - 我有 2 个列表,我想合并它们,答案应该如下所示

python - 如何在python中将一个字典结构转换为另一个字典

c++ - 如何根据另一个 vector 中给出的索引拆分 vector ?

c++ - 自包含链表

c++ - 重新启动游戏并重新实例化对象

c# - 按值对字典进行排序,该值是具有 DateTime 的对象