2017-04-21 33 views
-1

我想實現一個類,其實例名爲toto的屬性是一個動態數組我可以追加,讀取,寫入像一個tlist。 我寫這個:在D6什麼是一個類的動態數組作爲屬性的最短的實現是什麼

Tmodel = Class(TObject) 
     ftoto:array of single; 
     function gettoto(ind : integer):single 
     function gettotosize:integer; 
     procedure settoto(ind : integer;valeur:single); 
     property toto[ind:integer]:single read gettoto write settoto; 
     property totosize:integer read gettotosize; 
    end; 


    function Tmodel.gettoto(ind : integer):single; 
    begin 
    result:=ftoto[ind]; 
    end; 
    procedure Tmodel.settoto(ind : integer;valeur:single); 
    begin 
    setlength(ftoto,ind+1); 
    ftoto[ind]:=valeur; 
    end; 
    function Tmodel.gettotosize:integer; 
    begin 
    result:=length(ftoto); 
    end; 

它是正確的嗎?

回答

0

在您的toto屬性設置器中調用SetLength()是錯誤的。改變你的totosize屬性,而是給它一個setter來調整數組的大小。

type 
    TModel = class(TObject) 
    private 
    fToto: array of Single; 
    function GetToto(index: Integer): Single; 
    function GetTotoSize: Integer; 
    procedure SetToto(index: integer; value: Single); 
    procedure SetTotoSize(value: Integer); 
    public 
    property Toto[index: Integer]: Single read GetToto write SetToto; 
    property TotoSize: Integer read GetTotoSize write SetTotoSize; 
    end; 

function TModel.GetToto(index: Integer): Single; 
begin 
    Result := fToto[index]; 
end; 

procedure TModel.SetToto(index: Integer; value: Single); 
begin 
    fToto[index] := value; 
end; 

function TModel.GetTotoSize: Integer; 
begin 
    Result := Length(fToto); 
end; 

procedure TModel.SetTotoSize(value: Integer); 
begin 
    SetLength(fToto, value); 
end; 
+0

那麼析構函數呢?我應該添加一個freeandnil來避免泄漏? – bbd

+0

而不是猜測,閱讀文檔,它會告訴你,動態數組管理 –

+0

是否有可能DH不回答我的帖子,因爲它總是負面和無用的評論。預先提示: – bbd

相關問題