cpp初始化程序过多-数组中的struct

时间:2019-07-10 21:31:18

标签: c++ struct compiler-errors

几天以来,我对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'

对不起,我有点卡住了……也许只是来晚了:) 预先感谢。

1 个答案:

答案 0 :(得分:1)

首先,将menuItem item []数组包装在{}中,因为当前它认为存在很多数组,而不仅仅是一个。

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

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

#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}, }
    }
};