gpt4 book ai didi

c++ - cpp 太多初始化器 - 数组中的结构

转载 作者:行者123 更新时间:2023-11-28 04:14:23 25 4
gpt4 key购买 nike

我刚接触 cpp 几天,一直在为以下定义而苦苦挣扎:

struct menuItem {
char* name;
int value;
};

struct topMenu {
int menuIcon;
char* Name;
menuItem item[];
};

topMenu menuRoot[] = {
{ 0, "File",
{"Open ...", 1},
{"New ...", 4},
{"Close", 1},
{"Exit", 3}

},
{ 0, "Edit",
{"Cut ", 3},
{"Copy", 8},
{"Paste", 2},
{"Find", 1},
{"Replace", 6}

},
{ 0, "Help",
{"Help", 7},
{"About", 9},
{"Update ..", 9}
}
};

我收到错误

33:1: error: too many initializers for 'menuItem [0]'
33:1: error: too many initializers for 'topMenu'
33:1: error: too many initializers for 'menuItem [0]'
33:1: error: too many initializers for 'topMenu'
33:1: error: too many initializers for 'menuItem [0]'
33:1: error: too many initializers for 'topMenu'

抱歉,我有点卡住了……也许来晚了:)提前致谢。

最佳答案

首先,将 menuItem item[] 数组包裹在 {} 中,因为目前它认为有很多数组,而不是只有一个。

接下来,如前所述,将 char * 更改为 const char *。

现在对于灵活数量的 menuItem 结构,使用 vector 而不是数组。

#include <vector> 

struct menuItem {
const char *name;
int value;
};

struct topMenu {
int menuIcon;
const char *Name;
std::vector<menuItem> item;
};

topMenu menuRoot[] = {
{ 0, "File", {
{"Open ...", 1},
{"Open ...", 1},
{"Open ...", 1},
{"Open ...", 1},
}
},
{ 0, "Help", {
{"Open ...", 1},
{"Open ...", 1},
{"Open ...", 1}, }
}
};

关于c++ - cpp 太多初始化器 - 数组中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56978918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com