使用枚举 class 初始化结构成员时编译错误

Compile error initializing struct member with enum class

以下程序编译错误如下

// Example program
#include <iostream>
#include <string>

enum class Animation: int{
  Hide=0,
  Show,
  Flicker
};

struct Icon {
  int id;
  char name[10];
  Animation currentAnim; 
  Animation nextAnim;
  int isActive; 
};

static struct Icon IconList[]= {
    {1, "Offline", Animation::Hide, Animation::Hide, 1},
    {2, "Training", Animation::Hide, Animation::Hide, 1},
    {0, 0, Animation::Hide, Animation::Hide, 1}
};

int main()
{
  std::cout << "Doesn't matter";
}

编译

23:1: error: cannot convert 'Animation' to 'char' in initialization 23:1: error: cannot convert 'Animation' to 'char' in initialization

如果我将 IconsList[] 的最后一个成员更改为此,编译错误将得到修复。

{0, "", Animation::Hide, Animation::Hide, 1}

你能解释一下原因吗?为什么我会收到这样的案例编译错误消息?

如果我使用 int 而不是 enum class,我不会遇到这个编译错误

aggregate initialization

中可以省略嵌套初始化列表周围的大括号

The braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.

成员name是一个包含10个元素的子聚合,初始化器中的第2个0只是用来初始化name的第一个元素,然后Animation::Hide尝试用于初始化第二个和第三个元素;但 Animation 无法隐式转换为 char(作为 scoped enumeration)。

If I use int instead of enum class, I don't face this compilation error

那是因为 int 可以隐式转换为 char。请注意,对于这种情况,Icon 的某些成员可能未初始化。

如果您打算使用 0 来初始化成员 name,则可以为嵌套初始化程序添加大括号;作为效果name的第一个元素被初始化为0,所有剩余的元素也是value-initialized(zero-initialized)到0,就像用 "".

初始化它
static struct Icon IconList[]= {
    {1, "Offline", Animation::Hide, Animation::Hide, 1},
    {2, "Training", Animation::Hide, Animation::Hide, 1},
    {0, {0}, Animation::Hide, Animation::Hide, 1}
};