如何初始化嵌套结构数组
How to initialize an Array of Nested structures
我正在尝试编写一个程序来设置嵌套结构,然后初始化该结构的数组。 它给了我一些奇怪的错误。 以下是所有相关代码:
//Structure called Stats for storing initial character stats
struct Stats{
string name;
int level;
int HP;
int STR;
int CON;
int DEX;
int INT;
int WIS;
int CHA;};
//Structure called Growth for storing character growth per level.
struct Growth{
int HPperlvl;
int STRperlvl;
int CONperlvl;
int DEXperlvl;
int INTperlvl;
int WISperlvl;
int CHAperlvl;};
struct Holdstats{
Stats classstats;
Growth classgrowth;};
const int SIZE = 10;
Holdstats classlist[SIZE];
Holdstats charlist[SIZE];
//Define initial classes, to be stored in the Classes structure
classlist[0].classstats = {"Fighter", 1, 18, 10, 10, 10, 10, 10, 10};
classlist[0].classgrowth = {1,1,1,1,1,1,1};
classlist[1].classstats = {"Wizard", 1, 10, 10, 10, 10, 10, 10};
classlist[1].classgrowth = {1,1,1,1,1,1,1}
我的编译器认为,当我输入"classlist[0].classstats"时,我正在尝试初始化一个大小为 0 的数组。 我阅读本文的方式是我尝试访问类列表数组的第一个元素。 这写得对吗?
如果有人能给我一个简短的例子来说明这样的数组是什么样子的,那就太好了。 从那里开始,我正在考虑将其编写为向量
您没有展示所有类型是什么,但您应该能够采用这种基本方法。
Holdstats classlist[SIZE] = {
{ {"Fighter", 1, 18, 10, 10, 10, 10, 10, 10}, {1,1,1,1,1,1,1} },
{ {"Wizard", 1, 10, 10, 10, 10, 10, 10}, {1,1,1,1,1,1,1} },
}
>您的结构Holdstats
包含另外两个类型为 classstats
和 classgrowth
的结构。请记住,这些是结构,而不是数组,所以我不完全确定为什么你这样分配它们:
classlist[0].classstats = {"Fighter", 1, 18, 10, 10, 10, 10, 10, 10};
我猜你想在 holdstats 结构本身中填写统计结构,这将在下面完成:
classlist[0].classstats.health = 15; //guessing you have a member named health
//OR if you create a constructor for you classstats with the proper copy constructor
classlist[0].classstats = classstats("Fighter", 1, 18, 10, 10, 10, 10, 10, 10);
//OR if you have an assign function
classlist[0].classstats.assign("Fighter", 1, 18, 10, 10, 10, 10, 10, 10);
相关文章:
- C++将文本文件中的数据读取到结构数组中
- JSON转换为nlohmann JSON-lib中的结构数组
- 需要帮助将结构数组传递给函数
- 在 64 位边界上对齐C++结构数组?
- 带有枚举方向/类型的气泡排序结构数组
- 在C++中访问结构数组中的数据
- 从指向结构数组的指针中提取元素
- 如何制作一个地图,其中的值是C++中的结构数组
- 如何在函数中显示结构数组
- 包含作为成员C++函数的结构数组
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- std::transform 将一个结构数组复制到另一个结构数组
- 将非托管结构数组封送到托管数组
- 显示结构数组
- 结构数组中所有类似字段的总和
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 在 glsl opengl 中将嵌套结构数组作为统一传递
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何将字符串字符与结构数组进行比较?
- C++结构数组