我正在尝试创建一个物品和盒子系统,其中一个盒子可以在其中容纳灵活数量的物品(即,不要通过使每个盒子有 50 个物品而浪费内存,而有些盒子只有几个物品)。我不太确定该怎么做。
我尝试将 Item 结构作为灵活数组放入 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) };
}
std::vector
作为动态大小容器。std::string
这样的字符串使用
name
(而不是普通的 char
数组)。
下面演示了一个最小示例,初始化一个包含 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
}
备注:
Item
和 Box
添加构造函数。