1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include <stdio.h> #include <string.h> typedef void(*funcP)(void*); typedef void*(*virTabPointer)[2]; typedef struct Animal { virTabPointer m_virPointer; char m_name[20]; } Animal;
typedef struct Tiger { Animal m_base; int m_age; } Tiger;
typedef struct Bull { Animal m_base; char m_sex[6]; } Bull;
void SayName(void* this) { Animal* thisA = (Animal*)(this); printf("我的名字是:%s\n", thisA->m_name); }
void TigerEat(void* this) { Animal* thisA = (Animal*)(this); printf("我的名字是:%s,", thisA->m_name); Tiger* thisTiger = (Tiger*)(this); printf("今年%d岁,我吃肉\n", thisTiger->m_age); }
void BullEat(void* this) { Animal* thisA = (Animal*)(this); printf("我的名字是:%s,", thisA->m_name); Bull* thisBull = (Bull*)(this); printf("我的性别是:%s,我吃草\n", thisBull->m_sex); }
void TemplateFunc(Animal* obj) { void** tempIntPointer = (void**)(obj); virTabPointer tempVTab = (virTabPointer)(*tempIntPointer); funcP tempFuncAddress = (funcP)((*tempVTab)[1]); tempFuncAddress(obj); }
void* animalVirTab[2] = {(void*)&SayName, NULL}; void* tigerVirTab[2] = {(void*)&SayName, (void*)&TigerEat}; void* bullVirTab[2] = {(void*)&SayName, (void*)&BullEat};
int main() { Animal* basePointer = NULL; Tiger tigerA; basePointer = (Animal*)&tigerA; strcpy(basePointer->m_name, "老虎"); basePointer->m_virPointer = &tigerVirTab; tigerA.m_age = 5; TemplateFunc(basePointer); Bull bullA; basePointer = (Animal*)&bullA; strcpy(basePointer->m_name, "牛"); basePointer->m_virPointer = &bullVirTab; strcpy(bullA.m_sex, "男"); TemplateFunc(basePointer); return 0; }
|