开发者

Record in record (Cannot initialize)

I have 2 records like this:

TYPE
 TRecord2= packed record
  i2: Integer;
 end;

 TRecord1= packed record
  i1: Integer;
  R2: TRecord2;
 end;

.

I want to initialize the record fields to zero but I don't want to use FillMemory so I declared 2 constant records in which I initialize the fields.

CONST
  Record2c: TRecord2=
  (
   i2: 0;
  );

  Record1c: TRecord1=
  (
    i1: 0;
    R2: Record2c;      <------- error line
  );

However, I cannot assign a Record2c to R2 field. The compil开发者_C百科er says: E2029 '(' expected but identifier 'Record2c' found.

But this works (if I comment the line where I have the error):

procedure test;
var Record1: TRecord1;
begin
 Record1:= Record1c;      // initialize variable by associating the constant to it
end

So, how do i initialize the R2 field?


You can only initialize consts with true constants. True constants do not have types — those are typed constants. See Declared Constants in the Delphi documentation. Record2c in your code is a typed constant, so it cannot be used in const expressions like the one required for initializing Record1c. You'll just have to in-line the definition of Record1c.R2:

const
  Record1c: TRecord1 = (
    i1: 0;
    R2: (i2: 0;);
  );

When you comment out the error line, you're leaving the R2 field default-initialized to zeros.


That's because Record2c is a typed constant which isn't a "real" constant. So you can't use it to initialize another constant. You have to declare Record1c like

  Record1c: TRecord1 =
    (
    i1: 0;
    R2: (i2: 0);
    );


In Delphi-2009 and later it is possible to zero a record by the Default call.

record1 := Default(TRecord1);  // This will zero record1 including R2

See David's answer to the question How to properly free records that contain various types in Delphi at once?.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜