一个可能的解决方案是使用
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
}
笔记:
-
考虑通过将数据字段设为私有字段并提供访问器方法来封装这些字段。
-
考虑为添加构造函数
Item
和
Box
,可能还有其他方法,如
add_item
对于
盒
.