gpt4 book ai didi

arrays - 在类中实例化对象数组

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

我有一个项目需要使用预定义的类来与远程网络服务进行通信。主类包含标准字段以及在不同类中定义的对象数组。实例化主类不会实例化较低级别的类,从而产生 AV。下面的代码是该问题的可执行示例,其中尝试在“ProductLines”数组中插入数据会产生错误。

问题是如何实例化数组对象?尝试构造函数 setlength() 没有成功。非常感谢任何指导。

unit Unit1;

interface

uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Soap.InvokeRegistry;

type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

ProductLine = class(TRemotable)
private
Description: string;
Quantity: integer;
end;

ArrayOfProductLines = array of ProductLine;

Customer = class(TRemotable)
private
Name: string;
Comment: string;
ProductLines: ArrayOfProductLines;
end;

// Customer Class
// Name
// Comment
// ProductLines (array)
// ProductLine
// ProductLine
// .....
var
Form1: TForm1;
TObj : Customer; // Transfer object

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
TObj.Name := 'Test Name;';
TObj.Comment := 'Test Comment';


TObj.ProductLines[0].Description := 'Test Description 1'; // fails
here, how to instantiate?
TObj.ProductLines[0].Quantity := 1;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
Close;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
TObj := Customer.Create;
SetLength(Tobj.ProductLines,1);
end;

end.

最佳答案

The question is how to instantiate the array objects?

SetLength(TObj.ProductLines,1);

此行创建数组中的第一个元素并将其初始化为 nil。

为了创建对象,只需执行:

TObj.ProductLines[0] := ProductLine.Create;

请注意,ProductLines 数组中的每个实例化元素都必须手动销毁以避免内存泄漏。


关于 naming conventions 的注释:

  • 对于对象类型和一般类型,使用大写字母 T 作为首字母。示例 TCustomer
  • 对于变量,避免将大写字母 T 作为第一个字母。

关于arrays - 在类中实例化对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48956943/

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