小编pol*_*zed的帖子

带动态数组的DELPHI类与SetLength()有问题

我需要创建一个包含记录对象数组的,但是尝试使用SetLength会引发一个Access Violation错误.

请考虑以下带有水果的树对象示例.

type
TFruit = record
  color: string;
  weight: double;
end;

type
  TObjectTree = class

  Public
  Fruits: array of TFruit;

  constructor Create;
  procedure AddFruit;
end;
Run Code Online (Sandbox Code Playgroud)

在实现中,当尝试调整Fruit对象数组或初始化为nil时会产生问题.

constructor TObjectTree.Create;
begin
    inherited Create;
    Fruits:=nil;              //Raises an error
end;


procedure TObjectTree.AddFruit(FruitColor: string; FruitWeight: integer);
begin
    SetLength(Fruits, Length(Fruits)+1);  //Raises an error (when I comment Fruits:=nil; in the constructor)

    Fruits[Length(Fruits)].color:=FruitColor;      
    Fruits[Length(Fruits)].weight:=FruitWeight;
end;
Run Code Online (Sandbox Code Playgroud)

如何在类中使用动态数组?

arrays delphi class dynamic

2
推荐指数
3
解决办法
6240
查看次数

标签 统计

arrays ×1

class ×1

delphi ×1

dynamic ×1