gpt4 book ai didi

c++11 - 使用 c++11 枚举类时数组的大小具有非整数类型

转载 作者:行者123 更新时间:2023-12-02 23:04:16 26 4
gpt4 key购买 nike

我使用了这段代码:

enum E {
E1, E2, E3, MaxNum
};

const char * ENames[ MaxNum ] = {
"E1", "E2", "E3"
};

并且没有任何问题。现在我想使用“现代”枚举类。代码现在如下所示:

enum class E {
E1, E2, E3, MaxNum
};

const char * ENames[ E::MaxNum ] = {
"E1", "E2", "E3"
};

出现错误

error: size of array ‘ENames’ has non-integral type ‘E’

error: too many initializers for ‘const char* [1]’

问:为什么enum class在c++11中变得非整数,而通常的枚举是整数?

什么是问题的决策?如何声明一个具有大小的数组,即 enum class 中的枚举之一?

这里 - http://ideone.com/SNHTYe - 是一个简单的例子。

谢谢。

最佳答案

Q: why enum class does become non-integral in c++11, while usual enum is integral ?

因为它不是“通常的枚举”,所以它的类型更强

How can I declare an array with size, that is one of enumeration in enum class ?

为什么你还想这么做?您可以使用static_cast,但问题的解决方案是“不要这样做”。

如果您想要固定基础类型的枚举,请执行此操作,不要使用作用域枚举:

enum E : uint16_t {
E1, E2, E3, MaxNum
};

const char * ENames[ MaxNum ] = {
"E1", "E2", "E3"
};

关于c++11 - 使用 c++11 枚举类时数组的大小具有非整数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17359235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com