[英]In C++, how do I create a constexpr aggregate initialization for a struct that has an array of structs in it?
I am working in C++ and I want to create an initializer list for a struct of array of structs and I keep getting the same compilation error.我在 C++ 工作,我想为结构数组的结构创建一个初始化列表,但我一直遇到相同的编译错误。
Here is my struct:这是我的结构:
typedef struct SetpointChange
{
uint8_t hours;
uint8_t minutes;
} SetpointChangeTime_t;
typedef struct SetpointChangesDaySchedule
{
SetpointChangeTime_t dayChanges[4];
} SetpointChangesDaySchedule_t;
typedef struct SetpointChangesWeekSchedule
{
SetpointChangeTime_t weekChanges[2];
} SetpointChangesWeekSchedule_t;
Here is my initializer list:这是我的初始化列表:
static constexpr SetpointChangesWeekSchedule defaultSchedule = {
{
{0, 0},
{0, 0},
{0, 0},
{0, 0}
},
{
{0, 0},
{0, 0},
{0, 0},
{0, 0}
}
};
I am getting this error:我收到此错误:
error: too many initializers for 'SetpointProgram::SetpointChange_t [2]' {aka 'SetpointProgram::SetpointChange [2]'}
75 | };
| ^
My initialization syntax seems to be very correct... I don't understand why I am getting this error.我的初始化语法似乎非常正确...我不明白为什么会出现此错误。
This is aggregate initialization, not initializer list.这是聚合初始化,而不是初始化列表。 You need to double braces in some places:
你需要在某些地方加双括号:
#include <cstdint>
typedef struct SetpointChange
{
uint8_t hours;
uint8_t minutes;
} SetpointChangeTime_t;
typedef struct SetpointChangesDaySchedule
{
SetpointChangeTime_t dayChanges[4];
} SetpointChangesDaySchedule_t;
typedef struct SetpointChangesWeekSchedule
{
SetpointChangesDaySchedule_t weekChanges[2];
} SetpointChangesWeekSchedule_t;
static constexpr SetpointChangesWeekSchedule defaultSchedule = {{
{{
{0, 0},
{0, 0},
{0, 0},
{0, 0}
}},
{{
{0, 0},
{0, 0},
{0, 0},
{0, 0}
}}
}};
Explanation is: first braces are for object, second are for array inside object.解释是:第一个大括号是object,第二个是object里面的数组。
Compiler allows to use single set, like this:编译器允许使用单个集合,如下所示:
struct Test
{
int a[5];
};
Test t = {1, 2, 3, 4, 5};
But in your case it will look like:但在你的情况下,它看起来像:
static constexpr SetpointChangesWeekSchedule defaultSchedule = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
Which is probably too confusing.这可能太令人困惑了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.