3 回答

TA貢獻1875條經驗 獲得超5個贊
第一個C ++編譯器(“C with classes”)實際上會生成C代碼,所以這絕對可行。
基本上,你的基類是一個結構; 派生結構必須在第一個位置包含基本結構,因此指向“derived”結構的指針也將是指向基本結構的有效指針。
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
這些函數可以作為函數指針的結構的一部分,因此像p-> call(p)這樣的語法變得可能,但你仍然必須顯式地將指向結構的指針傳遞給函數本身。

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