【问题标题】:How to insert class into stl map on class initialization如何在类初始化时将类插入 stl 映射
【发布时间】:2013-07-13 21:01:33
【问题描述】:

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

我试图创建简单的物品系统,我可以通过它的 id 获取物品信息。我不能使用数组,因为项目 ID 可以说是随机的。我想使用声明的项目作为变量,我想通过它的 id 快速找到任何项目信息。我找到的唯一方法是stl map。

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

  1. main.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;
    }
    

由于某种原因程序崩溃了。如何在类初始化时正确地将类数据插入到地图中?

【问题讨论】:

  • 你的代码是递归的?当你创建一个项目时,它会创建一个项目等等......崩溃!!!
  • 感谢 alex 发现这个问题。

标签: c++ class map constructor initialization


【解决方案1】:

问题在于初始化的顺序。 brass_knucklesgolf_club 的静态构造函数首先运行,在 Stuff 的静态构造函数之前运行,因此它们会尝试插入到尚未构造的映射中。

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

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

extern const c_items brass_knuckles, golf_club;

【讨论】:

  • 感谢您,我更改了变量顺序,添加了项目的外部,将 Stuff[id] = c_items(...) 更改为 Stuff[id] = *this;问题解决了:)非常感谢。
【解决方案2】:

你不能像那样把 c_item 放在 Stuff 中 而是

 std::map<int,c_items> Stuff = { {item1.id, item1}, {item2.id, item2}};

但您还需要@Chris Dodd 提出的所有建议

所以

c_items::c_items(int id, char name[], int type) : id(id), type(type), name(name)
{}

extern const c_items  brass_knuckles,      golf_club;

在 main.cpp 中

 const c_items  brass_knuckles = {546, "Brass knuckles", weapon);
    const c_items golf_club = (2165, "Gold club", weapon);
    std::map<int,c_items> Stuff = { {brass_knuckles.id, brass_knuckles}, etc....};

【讨论】:

    猜你喜欢
    • 2010-10-05
    • 1970-01-01
    • 2019-01-28
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多