透過巨集套件 OOSM 模擬類別宣告與繼承關係:
#ifndef __CSQUA_H__
#define __CSQUA_H__
#include "crect.h"
class(csqua) {
extends(crect); /* 繼承自 crect */
};
#endif
class、extends 為巨集,展開後建立結構體並內嵌父類別結構體作為第一個成員,實現記憶體佈局相容。
#include "csqua.h"
static double peri(void *this)
{
return 4 * ((crect *)this)->width; // 正方形周長 = 4 * 邊長
}
static double area(void *this)
{
return ((crect *)this)->width * ((crect *)this)->width; // 面積 = 邊長²
}
constructor(csqua)
{
mapping(crect.imeas.peri, peri); // 將虛函式指標指向自已實作
mapping(crect.imeas.area, area);
}
destructor(csqua)
{
return 1; // 回傳 1 表示釋放記憶體
}
csqua 結構體第一個成員為 crect,指標轉換 (crect*)this 安全且零成本。imeas 包含函式指標;子類別建構子中用 mapping 巨集將指標指向自已實作。this,所有成員函式第一參數為 void*,呼叫時手動傳遞物件指標。constructor(csqua)、destructor(csqua) 由巨集展開為具體函式名。crect 結構體:
+------------------+
| width |
| height |
| imeas (vtable) | → { peri_func, area_func }
+------------------+
csqua 結構體 (繼承):
+------------------+
| crect (父類別) | ← 記憶體起始位址相同
| width |
| height |
| imeas | → 被建構子覆寫指向 csqua 實作
+------------------+
private/protected/public,靠命名慣例(_ 前綴)與紀律約束。obj->method(obj, ...) 顯得冗長。本系列展示:
證明面向物件是設計思維,非語言專利。C 語言雖無語法糖,但以紀律與巨集可實現核心機制,深入理解有助於掌握 C++ 底層模型。