gpt4 book ai didi

delphi - 不支持嵌套结构类型的嵌套常量?

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

尽管 Delphi 引用资料是这样说的

structured types can contain other structured types; a type can have unlimited levels of structuring

除了值得注意的异常(exception)之外,什么是结构化类型常量

cannot contain file-type values at any level

我发现我不能使用记录常量作为相同类型的数组常量的元素。

测试用例

type
MyRecord = record MyField: Integer end;

const
Typical: array[0..1] of MyRecord = ((MyField: 0), (MyField: 1));

{ now I tried to achieve more clarity by declaring a specific constant }
Zero: MyRecord = (MyField: 0);

{ and compiler refused to accept that }
Bad: array[0..1] of MyRecord = (Zero, (MyField: 1)); { E2029 '(' expected but identifier 'Zero' found }

我用几个 Borland 编译器测试了这段代码,它们都表现出相同的行为。 UPD:FPC 也相同,但 GPC 不同(!)。

问题

这是怎么回事?我在问题标题中的“不支持嵌套结构类型的嵌套常量”结论是否正确?对问题还有更多分析吗?

最佳答案

看来这是不可能的,根本原因是 ZeroRec 并不是真正的常量,它更像是一个初始化的静态变量。

如果{$WRITEABLECONST ON}被指定,那么它可以被简单地改变。即使 $WRITEABLECONST OFF,它也可以通过一些创意类型转换来更改(在 XE2 中测试):

program Project3;

{$APPTYPE CONSOLE}

{$R *.res}

uses
System.SysUtils;

type
MyRecord = record MyField: Integer end;
PMyRecord = ^MyRecord;

const
Typical: array[0..1] of MyRecord = ((MyField: 0), (MyField: 1));

{ now I tried to achieve more clarity by declaring a specific constant }
ZeroRec: MyRecord = (MyField: 0);
{ and compiler refused to accept that }
// Bad: array[0..1] of MyRecord = ((MyField: Zero), (MyField: 1)); { E2029 '(' expected but identifier 'Zero' found }
begin
try
{ TODO -oUser -cConsole Main : Insert code here }
WriteLn(ZeroRec.MyField);
PMyRecord(@ZeroRec)^.MyField := 2;
WriteLn(ZeroRec.MyField);
readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.

这将输出

0

2

对于简单类型,这种行为也很明显,

  Zero = 0;
ZeroRec: MyRecord = (MyField: Zero);

但是按预期编译

  Zero : Integer = 0;
ZeroRec: MyRecord = (MyField: Zero);

给出[DCC错误] Project3.dpr(19):E2026预期常量表达式

关于delphi - 不支持嵌套结构类型的嵌套常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16247819/

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