c++ - 为什么允许我使用不完整的枚举类?

标签 c++

为什么下面的代码编译没有任何错误?

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

Quoting cppreference

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/

相关文章:

c++ - 这怎么可能呢?

c++ - 如何在驱动程序代码中检查 unsigned char 指针是否为零?

c++ - 如何在 OpenCV 中获取网络摄像头 fps 速率?

c++ - 错误 : cannot open file 'boost_atomic-vc120-mt-1_58.lib' boost libs on Qt Windows8

c++ - 为什么这个指针包含存储在堆上的地址?

从函数返回字符串的 C++ 错误

java - 对 CXF 服务器的 C/C++ SSL 请求

c++ - lstd++ 和 extern - 从 C 调用 C++

c++ - 我应该默认虚拟析构函数吗?

c++ - 我如何访问一个指针子类方法,那些方法是子类独有的?