gpt4 book ai didi

record - FreePascal 中不同记录的标识符可以重复吗?

转载 作者:行者123 更新时间:2023-12-03 02:19:10 24 4
gpt4 key购买 nike

这是我的问题:我想创建一个记录类型,其中在变体记录的情况下,一些(但不是全部)将具有特定字段。根据wiki ,这是完全合法的。然而,当我尝试编译以下代码时:

program example;

{$mode objfpc}{$H+}

uses sysutils;

type
maritalStates = (single, married, widowed, divorced);

TPerson = record
name: record
first, middle, last: string;
end;
sex: (male, female);
dob: TDateTime;
case maritalStatus: maritalStates of
single: ( );
married, widowed: (marriageDate: TDateTime);
divorced: (marriageDate, divorceDate: TDateTime;
isFirstDivorce: boolean)
end;

var
ExPerson: TPerson;

begin
ExPerson.name.first := 'John';
ExPerson.name.middle := 'Bob';
ExPerson.name.last := 'Smith';
ExPerson.sex := male;
ExPerson.dob := StrToDate('05/05/1990');
ExPerson.maritalStatus := married;
ExPerson.marriageDate := StrToDate('04/01/2015');

end.

编译失败并出现以下错误:

$ fpc ex.pas
Free Pascal Compiler version 3.0.0 [2016/02/14] for x86_64
Copyright (c) 1993-2015 by Florian Klaempfl and others
Target OS: Win64 for x64
Compiling ex.pas
ex.pas(19,18) Error: Duplicate identifier "marriageDate"
ex.pas(21,3) Error: Duplicate identifier "marriageDate"
ex.pas(35,4) Fatal: There were 2 errors compiling module, stopping
Fatal: Compilation aborted
Error: C:\lazarus\fpc\3.0.0\bin\x86_64-win64\ppcx64.exe returned an error exitcode

维基是完全错误的,还是我在这里遗漏了一些东西?有什么办法可以达到我想要的效果吗?

最佳答案

非常有趣的问题。我确信这是可能的。如果您将代码修改为:

..
married, widowed, divorced: (marriageDate: TDateTime);
divorced: (divorceDate: TDateTime; isFirstDivorce: boolean)
..

它可以工作,但这不是您想要的结果。由于结婚日期和离婚日期相互重叠(如评论中所述!)

enter image description here

这张图片取自《Pascal 用户手册(第 4 版)》,您可以看到变体部分具有相同的内存位置。

根据Pascal users manual (4th edition)对于“Turbo Pascal ISBN 3-89011-060-6”一书,您引用的 wiki 上描述的记录声明无效!

  1. All field names must be distinct - even if they occur in different variants.
  2. If a variant is empty (i.e., has no fields), the form is: C:()
  3. A field list can have only one variant part and it must follow the fixed part of the record.
  4. A variant may itself contain a variant part; hence variant parts can be nested.
  5. The scope of enumerated type constant identifiers that are introduced in a record type extends over the enclosing block.

第 1 点与此处相关! 《Turbo Pascal》一书建议的解决方案是对多次出现的字段名称使用唯一的前缀。

在您的情况下,您可能会如下所示:

TPerson = record
name: record
first, middle, last: string;
end;
sex: (male, female);
dob: TDateTime;
case maritalStatus: maritalStates of
single: ( );
married, widowed: (marMarriageDate: TDateTime);
divorced: (divMarriageDate, divorceDate: TDateTime;
isFirstDivorce: boolean)
end;

另一个解决方案是将已婚、离婚......定义为记录类型。

..
married : (m: TMarried);
divorced : (d: TDivorced);
..

关于record - FreePascal 中不同记录的标识符可以重复吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36761256/

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