C++Builder 延伸標準 C++,引入 __property 關鍵字,讓類別像 Delphi 一樣擁有「屬性」語法:obj.Prop = 10; int x = obj.Prop; 實際呼叫讀寫存取函數。這不僅語法優雅,更能封裝驗證邏輯、延遲計算、事件觸發,是元件開發的核心機制。
class TSome {
protected:
int a, b, s;
int GetSum() { return s = a + b; } // 讀取器
void SetSum(int v) { s = v; a = v/2; b = v - a; } // 寫入器
public:
__property int Sum = { read = GetSum, write = SetSum }; // 讀寫屬性
__property int ReadOnly = { read = GetSum }; // 唯讀屬性
__property int WriteOnly = { write = SetSum }; // 唯寫屬性(罕用)
};
使用方式:
TSome obj;
obj.Sum = 100; // 呼叫 SetSum(100)
int v = obj.Sum; // 呼叫 GetSum()
class TSome {
private:
TList* FList;
protected:
void* GetItem(int idx) {
return (idx >= 0 && idx < FList->Count) ? FList->Items[idx] : nullptr;
}
void SetItem(int idx, void* ptr) {
if (idx >= 0 && idx < FList->Count) FList->Items[idx] = ptr;
else if (idx == FList->Count) FList->Add(ptr); // 自動擴充
}
int GetCount() { return FList->Count; }
public:
__fastcall TSome() { FList = new TList(); }
__fastcall ~TSome() { delete FList; }
__property void* Items[int idx] = { read = GetItem, write = SetItem };
__property int Count = { read = GetCount }; // 唯讀計數屬性
};
使用方式:
TSome obj;
obj.Items[0] = new TObject();
void* p = obj.Items[0];
int n = obj.Count;
| 屬性子句 | 說明 | 範例 |
|---|---|---|
default | 指定預設值,IDE 物件檢視器不顯示預設值 | __property int Tag = { default = 0 }; |
stored | 控制是否序列化到 DFM | __property int Value = { stored = false }; |
nodefault | 強制儲存(即使等於預設值) | __property int Value = { nodefault }; |
index | 多屬性共用同一存取函數,透過索引區分 | 見下文 |
class TRectEx {
private:
int coords[4]; // left, top, right, bottom
int GetCoord(int idx) { return coords[idx]; }
void SetCoord(int idx, int v) { coords[idx] = v; }
public:
__property int Left = { read = GetCoord, write = SetCoord, index = 0 };
__property int Top = { read = GetCoord, write = SetCoord, index = 1 };
__property int Right = { read = GetCoord, write = SetCoord, index = 2 };
__property int Bottom = { read = GetCoord, write = SetCoord, index = 3 };
};
Type GetX()、void SetX(Type);陣列屬性加 int Index 參數。try/__finally 保護資源,避免屬性存取拋出異常導致 IDE 崩潰或資料損壞。Get 應為純查詢,不修改狀態;Set 才觸發變更通知、重繪等。__published 區塊聲明才會出現在物件檢視器並支援流式存取。__property 是 C++Builder 元件化的基石。掌握 標量、陣列、index 共用、存取控制 四大模式,配合 default/stored/nodefault 微調序列化行為,即可開發出專業級、IDE 深度整合的 VCL 元件。