代码之家  ›  专栏  ›  技术社区  ›  Robin Bubeník

如何在另一个结构中创建一个灵活的结构?

  •  0
  • Robin Bubeník  · 技术社区  · 3 周前

    我正在尝试创建一个物品和盒子系统,在这个系统中,一个盒子里可以有灵活数量的物品(即,不要浪费内存,让每个盒子都有50个物品,而有些盒子只有几个)。我不太确定该怎么做。

    我试着把 Item struct 内部 Box 结构 作为一个灵活的数组,但它实际上并不起作用。

    这是我的代码:

    struct Item {
        char name[64];
        char slot;
        int weight;
        int size;
        int dmg;
    };
    
    struct Box {
        int size;
        Item items[size];
    };
    
    int main()
    {
        Item sword = { "Sword", 'W', 20, 8, 5};
        Box box = { 3, (sword, sword, sword) };
    }
    
    1 回复  |  直到 3 周前
        1
  •  4
  •   wohlstad    3 周前

    一个可能的解决方案是使用 std::vector 作为动态大小的容器。

    您还应该使用 std::string 对于像这样的字符串 name (而不是平原 char 大堆在其他建议中,它将取消您现在拥有的63个字符的名称长度限制。

    下面展示了一个最小的例子,初始化一个有3个项目的盒子,然后添加1个项目:

    #include <string>
    #include <vector>
    
    struct Item {
        std::string name;
        char slot;
        int weight;
        int size;
        int dmg;
    };
    
    struct Box {
        std::vector<Item> items;
    };
    
    int main()
    {
        Item sword = { "Sword", 'W', 20, 8, 5 };
        Box box;
        box.items = { sword, sword, sword }; // initialize with 3 items
        box.items.push_back(sword);          // add another item
    }
    

    笔记:

    1. 考虑通过将数据字段设为私有字段并提供访问器方法来封装这些字段。
    2. 考虑为添加构造函数 Item Box ,可能还有其他方法,如 add_item 对于 .