繁体   English   中英

在struct中使用struct数组时,在标量初始化程序周围加括号

[英]Braces around scalar initializer when using array of struct in a struct

我正在尝试制作一个简单的菜单。 为此,我想使用一个结构为Menu并包含菜单项的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,
        }
    }
};

但我总是得到错误

标量初始值设定项周围的括号,用于“ const menuitem_t *”类型

...在结构中使用结构数组时

您没有结构数组。 您有一个指向 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,
    },
};

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

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中进行介绍。
  • 由于字符串字面量在C ++中是const,因此无法使用字符串文字量来初始化char* (因为C ++ 11;不建议在此转换之前使用)。 将成员更改为const char* ,或使用可变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()
{
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM