c++ - 使用 int 进行枚举类初始化

标签 c++ enums initialization c++17

我在编程的时候发现了一些有趣的事情:

enum class Foo {
  FOO_THING,
  FOO_TOO
};

int main() {
  Foo foo{1};    // It is OK
  Foo foo2(1);   // It is an invalid
}

你能告诉我,为什么 foo{1} 对于编译器来说是可以的,而为什么 foo2(1) 是无效的?

编译器 GCC (g++ (Ubuntu 7.3.0-21ubuntu1~16.04) 7.3.0) 说:

$ g++ -Wall -std=c++17 foo.cpp

  error: cannot convert ‘int’ to ‘Foo’ in initialization
  Foo foo2(1);

我真的很想知道底层机制。 :)))

编辑:可能是一些编译器错误...

最佳答案

C++17 特定 documentation有以下花括号初始化器

Otherwise, if T is a enumeration type that is either scoped or unscoped with fixed underlying type, and if the braced-init-list has only one initializer, and if the conversion from the initializer to the underlying type is non-narrowing, and if the initialization is direct-list-initialization, then the enumeration is initialized with the result of converting the initializer to its underlying type.

所以 foo 似乎符合有效的 C++17,但是 foo2 没有被初始化是无效的。

关于c++ - 使用 int 进行枚举类初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50717751/

相关文章:

c++ - 检测是否按下 Control+some 键的推荐方法是什么?

c++ - 使用 Directx 10 时,我得到了很多宏重新定义

c# - 创建一个没有 0 值的 C# 枚举实例

c++ - 为什么可以将枚举作为函数变量传递但不能返回枚举?

c++ - 如何初始化和定义指向二维数组的指针?

java - 静态成员初始化取决于另一个类成员的初始化

c++ - Qt 当主应用程序完全加载所有小部件时如何打开 QDialog

c++ - 单个连接上的多个数据库事务

c++文件不会用某个#include编译,而所有其他的都可以

c# - 提供的类型必须是枚举