我需要创建一个包含记录对象数组的类,但是尝试使用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)
如何在类中使用动态数组?