gpt4 book ai didi

c++ - 枚举类型值作为 C++ 中数组的长度

转载 作者:可可西里 更新时间:2023-11-01 18:32:13 25 4
gpt4 key购买 nike

众所周知,C++中的数组长度是必须确定的。然后我们可以使用:

const int MAX_Length=100;

或:

#define MAX_LENGTH 100

在编译前确定数组的长度。但是,当我阅读 lippman 的《c++ primer》一书时,在第 5 版的第 3.5.1 章中,它说:数组的长度必须是常量表达式。那么问题来了:

typedef enum Length{LEN1=100, LEN2, LEN3, LEN4}LEN; 
LEN MAX_Length=LEN2; //101
int iArray[LEN2]; //attention

代码在mingw32-g++中编译成功。但是在VS2008中失败了,错误是:

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'iArray' : unknown size

而且我认为枚举值是常量,所以它应该用作数组的长度。对吧?

我很困惑,你能帮帮我吗?谢谢。

最佳答案

在 C++11 和 C++03 中,枚举数(C++11 中的无作用域枚举)是整数常量表达式,因此可用于数组边界。我们可以通过转到 draft C++11 standard 来查看 C++11 的这一点。 5.19 [expr.const] 部分说:

An integral constant expression is an expression of integral or unscoped enumeration type, implicitly converted to a prvalue, where the converted expression is a core constant expression. [ Note: Such expressions may be used as array bounds (8.3.4, 5.3.4), as bit-field lengths (9.6), as enumerator initializers if the underlying type is not fixed (7.2), as null pointer constants (4.10), and as alignments (7.6.2). —end note ]

and or C++03 我们可以从 C++03 标准草案或 closest we can get 中看到这一点相同的段落 1 说:

[...]An integral constant-expression can involve only literals of arithmetic types (2.13, 3.9.1), enumerators, non-volatile const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type template parameters of integral or enumeration types, and sizeof expressions[...]

在 rextester 上此代码 compiles fine对于 VC++,所以这在当前版本中不再是一个问题,这一定是 2008 年的一个错误,最终得到修复。还在 webcompiler 上进行了测试最后更新于 2015 年 12 月 3 日,因此这也适用于最新版本之一。

一个替代方案可能是使用 const int 例如:

const int len = LEN2 ;

这将取决于 Visual Studio 2008 是否认为枚举数不是整数常量表达式,或者它是否只是在数组边界的上下文中,希望是后者。

C++98

据我所知,这也适用于 C++98,gccclang 在使用 -std=c+ 时都允许这样做+98,没有公开的 C++98 标准草案,所以我可以确认更多。

关于c++ - 枚举类型值作为 C++ 中数组的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25395672/

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