建構函式與解構函式

類、類實例、建構函式、解構函式

上方範例中包含 TAnimal 與其子類別 TDog類僅是一種型別,可將其理解為樣板,類本身不會儲存任何資料,範例中的欄位 MyInt: Integer 不會配置記憶體。

雖然透過類變數可讓類自身持有資料,此處先不討論,僅說明具備一般欄位的標準類別。

若要為欄位配置記憶體,必須建立類實例;建立實例需呼叫建構函式

若從未建立類的實例,該類的程式碼等同不存在,不會執行、也不會為其變數配置記憶體,就如同模具一般,唯有使用時才會配置記憶體;不使用時,它會靜置存放,不佔用資源。

建構函式

  • 特殊方法,使用關鍵字 constructor 宣告;
  • 系統會先配置物件記憶體,才執行建構函式程式碼;
  • 所有類別隱式繼承 TObject,內建無參數建構子 Create,不手動撰寫也可直接使用;
  • 自訂建構子是初始化物件的最佳方式,可在建構函式內為欄位指派初始值;
  • 自訂建構子慣例命名為 Create

範例

program Demo;
{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}
{$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}
{$codepage utf8}
uses SysUtils;

type
  TAnimal = class
  private
    InternalStuff: TObject;
  public
    constructor Create;
    destructor Destroy; override;
  end;

constructor TAnimal.Create;
begin
  inherited Create; // 開頭先呼叫父類建構子
  InternalStuff := TObject.Create;
  Writeln('執行 TAnimal.Create 建構函式');
end;

destructor TAnimal.Destroy;
begin
  Writeln('執行 TAnimal.Destroy 解構函式');
  FreeAndNil(InternalStuff); // 釋放內部子物件
  inherited Destroy; // 結尾呼叫父類解構子
end;

var
  C: TAnimal;
begin
  C := TAnimal.Create;
  try
    // 使用物件
  finally
    FreeAndNil(C); // 自動呼叫 Destroy 解構函式
  end;
end.

執行結果

D:\fpcdemo>fpc mydemo.dpr
Free Pascal Compiler version 3.2.2 [2021/05/15] for i386
Copyright (c) 1993-2021 by Florian Klaempfl and others
Target OS: Win32 for i386
Compiling mydemo.dpr
Linking mydemo.exe
38 lines compiled, 0.1 sec, 68672 bytes code, 4260 bytes data

D:\fpcdemo>mydemo
執行 TMyClass.Create 建構函式
執行 TMyClass.Destroy 解構函式Code language: CSS (css)

InternalStuff 是類內部持有的子物件。建立於建構函式,解構時必須透過 FreeAndNil 釋放,避免記憶體洩漏。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *