首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

C++Builder 自訂屬性完全指南:從標量到陣列屬性的聲明與實現

     編輯:VC 教學

前言:為什麼需要 __property?

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多屬性共用同一存取函數,透過索引區分見下文

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 };
};

四、關鍵注意事項與最佳實踐

  1. 存取函數必須為成員函數,不可為 static 或全域函數。
  2. 讀寫函數簽名固定:Type GetX()、void SetX(Type);陣列屬性加 int Index 參數。
  3. 異常安全:商業級元件務必在存取函數內 try/__finally 保護資源,避免屬性存取拋出異常導致 IDE 崩潰或資料損壞。
  4. 避免副作用:Get 應為純查詢,不修改狀態;Set 才觸發變更通知、重繪等。
  5. 發佈屬性:需在 __published 區塊聲明才會出現在物件檢視器並支援流式存取。

五、總結

__property 是 C++Builder 元件化的基石。掌握 標量、陣列、index 共用、存取控制 四大模式,配合 default/stored/nodefault 微調序列化行為,即可開發出專業級、IDE 深度整合的 VCL 元件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved