【问题标题】:dynamic array as type in delphi/pascal object动态数组作为 delphi/pascal 对象中的类型
【发布时间】:2020-01-30 13:05:21
【问题描述】:

我有一个单元,其中有多个变量必须是相同大小的向量。

但是在我解析文件之前我不知道这个数组的长度。

所以我想要一个对整个单元“全局”的动态数组,然后我可以

下面的代码显示了问题以及我现在的解决方案。我现在的解决方案是将最大值分配为数组的长度。

unit xyz;
interface 

uses
abc

const
maxval=50;

type
vectorofdouble = [1...maxval] of double;  // I want to change this to dynamic array

type
  T_xyz = object

  public
    NP: integer;
  private
    var1: vectorofdouble;        
    var2: vectorofdouble;        
   public
    number: integer;       
    var3: vectorofdouble; 

  private
    procedure Create();
    function func1(etc): integer;
  public
    procedure ReadFile(const FileName, inputs: string);
  end;

implementation
procedure T_xyz.ReadFile();
////////
Read(F,np)
  //SetLength(vectorofdouble, np) // DOES NOT WORK
  for i := 0 to maxval // I DONT WANT TO LOOP UP TO MAXVAL
  begin
    var1[i] := 0
  end;

procedure T_xyz.func1(etc);
////////
do stuff
  for i := 0 to maxval // I DONT WANT TO LOOP UP TO MAXVAL
  begin
    var2[i] := 0
  end;
end;

end.

【问题讨论】:

  • @Brian 一旦我从 vectorofdouble = [1...maxval] of double 改变;到vectorofdouble = double数组;我无法真正访问代码 setlength 中的任何地方的 vectorofdouble 给出错误
  • 您需要将数组而不是类型传递给SetLength。例如,SetLength(var1, ...)。顺便问一下,OFlex 代表什么?
  • 德尔福 10.3 Rio。如果我使用“vectorofdouble=array of double;”在类型下(见上文)和 f.e 添加一个 SetLength(vectorofdouble,10);在任何函数中 [dcc32 Error] filename.pas(438): E2029 '(' expected but ',' found
  • 我的评论解释了问题所在
  • @DavidHeffernan 这是我处理上面示例的主要代码只是一个假人。 SetLength(var1, ...) 工作正常,但是我有 30 个从 vectorofdouble var1、var2 varxxx “继承”的变量。上面的代码允许它被分配一次,而不是为每个变量分配一个方法

标签: delphi pascal


【解决方案1】:

您想使用dynamic array 而不是fixed-length array。您可以使用

array of <Type>

而不是

array[<Low>..<High>] of <Type>

那么SetLength() 就可以了,但是你需要给它传递一个动态数组variable 而不是type

试试这个:

unit xyz;

interface

uses
  abc;

type
  vectorofdouble = array of double;

type
  T_xyz = object
  public
    NP: integer;
  private
    var1: vectorofdouble;
    var2: vectorofdouble;
  public
    number: integer;
    var3: vectorofdouble;
  private
    procedure Create();
    function func1(etc): integer;
  public
    procedure ReadFile(const FileName, inputs: string);
  end;

implementation

procedure T_xyz.ReadFile();
var
  i: integer;
begin
  Read(F, NP);
  SetLength(var1, NP);
  for i := 0 to NP-1 do
  begin
    var1[i] := 0;
  end;
end;

procedure T_xyz.func1(etc);
begin
  for i := Low(var2) to High(var2) do
  begin
    var2[i] := 0;
  end;
end;

end.

【讨论】:

  • 我不确定要回答这个答案,因为:var2 缺少一个 setlength(var2,Np) 参数,这可能会产生误导,好像只分配 var1 就足够了。
【解决方案2】:

您必须将数组传递给SetLength 而不是类型。所以不是

SetLength(vectorofdouble, np)

你必须使用

SetLength(var1, np)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多