为什么下面的代码编译没有任何错误?
enum class Enumeration;
void func()
{
auto enumeration = static_cast<Enumeration>(2);
auto value = static_cast<int>(enumeration);
}
最佳答案
它编译是因为编译器在编译时知道 Enumeration
的大小(恰好是空的)。
您可以使用以下语法明确地看到它:
enum class Enumeration : short;
编译器知道关于Enumeration
的所有信息。
Enumeration
是一个opaque-enum-declaration 这也意味着该类型是完整的
即您可以使用 sizeof
它。如果需要,您可以在以后的重新声明中指定枚举器列表(显然,除非重新声明带有不同的基础类型)。
请注意,由于您正在使用 enum class
,因此必须使用 static_cast
。
- 强类型枚举不允许隐式转换为
int
,但您可以安全地对它们使用static_cast
来检索它们的整数值。
毕竟它们仍然是enum
。
There are no implicit conversions from the values of a scoped enumerator to integral types, although static_cast may be used to obtain the numeric value of the enumerator.
更多关于此主题的信息:How to automatically convert strongly typed enum into int?
关于c++ - 为什么允许我使用不完整的枚举类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45015280/