3 回答

TA貢獻(xiàn)1875條經(jīng)驗 獲得超5個贊
第一個C ++編譯器(“C with classes”)實際上會生成C代碼,所以這絕對可行。
基本上,你的基類是一個結(jié)構(gòu); 派生結(jié)構(gòu)必須在第一個位置包含基本結(jié)構(gòu),因此指向“derived”結(jié)構(gòu)的指針也將是指向基本結(jié)構(gòu)的有效指針。
typedef struct {
data member_x;
} base;
typedef struct {
struct base;
data member_y;
} derived;
void function_on_base(struct base * a); // here I can pass both pointers to derived and to base
void function_on_derived(struct derived * b); // here I must pass a pointer to the derived class
這些函數(shù)可以作為函數(shù)指針的結(jié)構(gòu)的一部分,因此像p-> call(p)這樣的語法變得可能,但你仍然必須顯式地將指向結(jié)構(gòu)的指針傳遞給函數(shù)本身。

TA貢獻(xiàn)1804條經(jīng)驗 獲得超2個贊
C ++離C不遠(yuǎn)。
類是具有指向名為VTable的函數(shù)指針表的隱藏指針的結(jié)構(gòu)。Vtable本身是靜態(tài)的。當(dāng)類型指向具有相同結(jié)構(gòu)的Vtables但指針指向其他實現(xiàn)時,您將獲得多態(tài)性。
建議將調(diào)用邏輯封裝在以struct為參數(shù)的函數(shù)中,以避免代碼混亂。
您還應(yīng)該在函數(shù)中封裝結(jié)構(gòu)實例化和初始化(這相當(dāng)于C ++構(gòu)造函數(shù))和刪除(C ++中的析構(gòu)函數(shù))。無論如何這些都是很好的做法。
typedef struct{ int (*SomeFunction)(TheClass* this, int i); void (*OtherFunction)(TheClass* this, char* c);} VTable;typedef struct{ VTable* pVTable; int member;} TheClass;
要調(diào)用方法:
int CallSomeFunction(TheClass* this, int i){ (this->pVTable->SomeFunction)(this, i);}
- 3 回答
- 0 關(guān)注
- 598 瀏覽
添加回答
舉報