在结构中使用结构数组时在标量初始值设定项周围加括号

Braces around scalar initializer when using array of struct in a struct

我正在尝试制作一个简单的菜单。为此,我想使用一个结构,它是菜单并包含一个菜单项的结构数组。

主菜单 - 程序 - 设置

菜单项包含一些进一步的信息,例如回调。

struct menu_t {
    char* text;
    const uint32_t num;
    const struct menuitem_t *contents[MAX_MENU_CONTENTS];
};

struct menuitem_t {
    char* text;
    uint8_t type;
    void (*callback)(void);
}

static const struct menu_t mainMenu[] = {
    .name = "Main Menu",
    .num = 3,
    .contents = {
        {
        .text = "Programms",
        .type = MENU_SUB,
        .callback = 0,
        },
        {
        .text = "Settings",
        .type = MENU_SUB,
        .callback = 0,
        }
    }
};

但我总是得到错误

braces around scalar initializer for type 'const menuitem_t*'

... when using array of struct in a struct

您没有结构数组。你有一个指针数组要构造。

要创建 N 个对象,您需要这些对象的数组。例如在这种情况下:

static const struct menuitem_t menu_items[MAX_MENU_CONTENTS] {
    {
    .text = "Programms",
    .type = MENU_SUB,
    .callback = 0,
    },
    {
    .text = "Settings",
    .type = MENU_SUB,
    .callback = 0,
    },
};

如果您不想将这些对象存储在 class 中,您可以初始化指向该数组中对象的指针:

static const struct menu_t mainMenu[] = {
    .name = "Main Menu",
    .num = 3,
    .contents = {
        menu_items + 0,
        menu_items + 1,
    },
};

您的程序的其他问题:

  • menu_t 没有成员 .name,但您尝试初始化它。您是说 .text 吗?
  • 指定的初始化器还不是任何已发布的 C++ 标准的一部分。它们将在即将到来的 C++20 中引入。
  • char* 不能用字符串文字初始化(自 C++11 起;在此之前转换已弃用),因为字符串文字在 C++ 中是常量。将成员更改为 const char*,或使用可变字符数组。

如果它确实是 C++17 代码,那么你有很多错别字。

例如结构 menu_t 不包含数据成员 name.

数据成员contents是一个指针数组。但是它不是由指针初始化的。

在 C++ 中,字符串文字具有常量字符数组类型。因此,结构中由字符串文字初始化的相应指针必须具有限定符 const.

如果要初始化聚合,则其初始化列表必须用大括号括起来。

下面有一个演示程序,展示了如何初始化您的结构。

#include <iostream>
#include <cstdint>

enum { MENU_SUB };
const size_t MAX_MENU_CONTENTS = 2;

struct menuitem_t;

struct menu_t {
    const char * name;
    const uint32_t num;
    const menuitem_t *contents[MAX_MENU_CONTENTS];
};

struct menuitem_t {
    const char *text;
    uint8_t type;
    void (*callback)(void);
};

static const struct menu_t mainMenu[] = 
{
    {
        .name = "Main Menu",
        .num = 3,
        .contents = 
        {
            new menuitem_t 
            {
                .text = "Programms",
                .type = MENU_SUB,
                .callback = nullptr,
            },
            new menuitem_t 
            {
                .text = "Settings",
                .type = MENU_SUB,
                .callback = nullptr,
            }
        }            
    }
};

int main()
{
}