gpt4 book ai didi

arrays - Delphi XE6 中使用枚举声明数组错误

转载 作者:行者123 更新时间:2023-12-03 15:15:26 25 4
gpt4 key购买 nike

当我声明这样的枚举时:

TConfigBaudRate = (br9600 = 6, br19200 = 8);

并尝试将此枚举与数组一起使用,如下所示:

const
CBaudRates: array [TConfigBaudRate] of string = ('9600', '19200');

Delphi 返回以下错误:

E2072 Number of elements (2) differs from declaration (3)

但是,如果我声明 TConfigBaudRate 时没有值或第一个项目的值,它就可以工作。

Delphi 似乎创建了一个数字 7 的元素。这是 Delphi 的正常特性吗?我找不到任何引用。

最佳答案

这是有记录的行为。

来自Simple Types - Enumerated Types with Explicitly Assigned Ordinality :(强调我的)

By default, the ordinalities of enumerated values start from 0 and follow the sequence in which their identifiers are listed in the type declaration. You can override this by explicitly assigning ordinalities to some or all of the values in the declaration. To assign an ordinality to a value, follow its identifier with = constantExpression, where constantExpression is a constant expression that evaluates to an integer. For example:

type Size = (Small = 5, Medium = 10, Large = Small + Medium);

defines a type called Size whose possible values include Small, Medium, and Large, where Ord(Small) returns 5, Ord(Medium) returns 10, and Ord(Large) returns 15.

An enumerated type is, in effect, a subrange whose lowest and highest values correspond to the lowest and highest ordinalities of the constants in the declaration. In the previous example, the Size type has 11 possible values whose ordinalities range from 5 to 15. (Hence the type array[Size] of Char represents an array of 11 characters.) Only three of these values have names, but the others are accessible through typecasts and through routines such as Pred, Succ, Inc, and Dec. In the following example, "anonymous" values in the range of Size are assigned to the variable X

var 
X: Size;
X := Small; // Ord(X) = 5
X := Size(6); // Ord(X) = 6
Inc(X); // Ord(X) = 7

因此,对于您的示例,即使您只使用了其中两个值(6 和 8),7 也是一个包含值,即使它没有命名,因为它属于分配的序数范围内,就像所描述的 Char 数组[Size] 将表示一个包含 11 个字符的数组。

关于arrays - Delphi XE6 中使用枚举声明数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27659564/

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