如何初始化嵌套结构数组

How to initialize an Array of Nested structures

本文关键字:结构 数组 嵌套 初始化      更新时间:2023-10-16

我正在尝试编写一个程序来设置嵌套结构,然后初始化该结构的数组。 它给了我一些奇怪的错误。 以下是所有相关代码:

//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包含另外两个类型为 classstatsclassgrowth 的结构。请记住,这些是结构,而不是数组,所以我不完全确定为什么你这样分配它们:

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);