malloc/new 分配、較慢但靈活、空間大、手動釋放 (free/delete)、存遞迴結構/長字串Object Pascal (Delphi/VCL) 物件只能建構於堆,不像 C++ 可置於堆疊、資料段、堆三處。因此 VCL 元件必須用 new 動態建立。
// 1. 取得記憶體空間
TButton *myBtn = new TButton(Form1); // 參數為 Owner (負責釋放)
// 2. 指定父容器 (關鍵!否則不會顯示)
myBtn->Parent = Form1;
// 3. 設定幾何屬性 (位置與大小)
myBtn->Top = 200;
myBtn->Left = 200;
myBtn->Height = 25;
myBtn->Width = 75;
// 4. 設定其他重要屬性
myBtn->Caption = "I'm Button!";
// Visible 預設 true,通常可省略
順序不可顛倒:Parent 必須在幾何屬性之前設定,否則座標系統錯誤。
void __fastcall TForm1::Button1Click(TObject *Sender) {
TButton *myBtn = new TButton(Form1);
myBtn->Parent = Form1;
myBtn->Top = 200;
myBtn->Left = 200;
myBtn->Height = 25;
myBtn->Width = 75;
myBtn->Caption = "I'm Button!";
}
動態建立第三方元件 (如 QuickReport) 需包含對應標頭:
#include "Qrctrls.hpp"
#include "QuickRpt.hpp" // 若仍有問題再加入
Form1 (表單)、this (當前物件)、NULL (手動管理) —— 推薦用表單/父容器,利用 Ownership 機制自動釋放// 動態建立 Panel 並在其中放入元件
TPanel *pnl = new TPanel(Form1);
pnl->Parent = Form1;
pnl->Top = 100; pnl->Left = 100; pnl->Width = 300; pnl->Height = 200;
TEdit *edt = new TEdit(pnl); // Owner = Panel
edt->Parent = pnl; // Parent = Panel
edt->Top = 10; edt->Left = 10;
Owner 機制:表單銷毀時自動釋放所擁有元件delete component; (會自動從 Owner 移除)Parent 與 Owner 概念不同,勿混淆TComponentList 或智慧指標管理