本文以銀行交易(存款/提款/轉帳)為領域模型,示範 C++/CLI 繼承體系、CLI 列舉型別、陣列繼承、覆寫與隱藏語意、存取修飾詞擴展。
public enum class TransactionType : unsigned char {
Deposit, Withdrawal, Transfer
};
差異於原生 enum:
enum class 關鍵字標記 CLI 列舉(CLS 相容)。int,此例 unsigned char)。TransactionType::Deposit。隱含繼承 System::Enum,可用靜態方法反射:
Enum::GetName(type, value); // 取得名稱
Enum::GetNames(type); // 所有名稱陣列
Enum::GetUnderlyingType(typeid); // 底層型別
public ref class Transaction abstract {
TransactionType type;
DateTime dt;
protected:
Transaction(TransactionType t) {
Thread::Sleep(Random()->Next(1000,2001)); // 模擬延遲
type = t; dt = DateTime::Now;
}
public:
property TransactionType Type { TransactionType get() { return type; } private: void set(TransactionType v) { type = v; } }
property DateTime Time { DateTime get() { return dt; } private: void set(DateTime v) { dt = v; } }
virtual void PostTransaction() abstract; // 純虛擬
};
abstract 修飾類別/方法(非關鍵字,上下文保留字)。public get / private set)。protected 僅供衍生類別呼叫。public ref class Deposit sealed : Transaction {
Decimal amount; int toAcct;
public:
Deposit(double a, int acct) : Transaction(TransactionType::Deposit) { amount = (Decimal)a; toAcct = acct; }
Deposit(Decimal a, int acct) : Transaction(TransactionType::Deposit) { amount = a; toAcct = acct; }
property Decimal Amount { Decimal get() { return amount; } private: void set(Decimal v) { amount = v; } }
property int ToAccount { int get() { return toAcct; } private: void set(int v) { toAcct = v; } }
void PostTransaction() { Console::WriteLine("{0} -- {1}", Time, this); }
virtual String^ ToString() override { return String::Format(" Dep: {0,10:0.00} {1,10}", Amount, ToAccount); }
};
sealed 禁止進一步繼承(設計意圖明確)。Decimal 適合金融計算。double/Decimal)。{0,10:0.00}:寬度 10、右對齊、兩位小數。array<Transaction^>^ list = gcnew array<Transaction^> {
gcnew Deposit(123.05, 12345),
gcnew Transfer(Decimal::Parse("1256.40"), 1111, 222),
gcnew Withdrawal(34.54, 232323),
gcnew Deposit(56.12, 14321)
};
for each (Transaction^ t in list) t->PostTransaction();
輸出顯示各交易時間與格式化明細,驗證虛擬函數動態派發。
所有 CLI 陣列隱含繼承 System::Array,擁有 Length、Sort、BinarySearch、Copy、Clear 等靜態/實例方法:
array<int>^ a = gcnew array<int>{10,75,23,18,53,18};
Array::Sort(a); Array::Reverse(a); Array::Copy(a, b, 4);
| 修飾詞 | 行為 | 動態派發 |
|---|---|---|
virtual ... override | 覆寫基底虛擬函式 | 是 |
virtual ... new | 隱藏基底虛擬函式,新虛擬槽位 | 否(靜態型別決定) |
new(非虛擬) | 隱藏基底非虛擬函式 | 否 |