纯C实现多态

用 C 模拟 C++ 中虚指针和虚表的机制。

#include<stdio.h>
#include <stdlib.h>
typedef struct Vtable{
    void (*fun)(void*);
    void (*Destructure)(void*);
}Vtable;

typedef struct Base{
    struct Vtable * vprt;
} Base;


typedef struct DeriveA{
    Vtable * vprt;
    int data;
} DeriveA;

void DeriveAFun(void* this){
    printf("DeriveAFun %d\n",((DeriveA*)this)->data);
}

void DeriveADestructure(void* deriveA){
    free(deriveA);
}

Vtable DeriveAVtable={
    DeriveAFun,
    DeriveADestructure
};
DeriveA* DeriveAStructure(int v){
    DeriveA* tmp= (DeriveA*)malloc(sizeof(DeriveA));
    tmp->vprt=&DeriveAVtable;

    tmp->data=v;

    return tmp;
}


typedef  struct DeriveB{
    Vtable * vprt;
    char data;
} DeriveB;

void DeriveBFun(void* this){
    
    printf("DeriveBFun %c\n",((DeriveB*)this)->data);
}

void DeriveBDestructure(void* deriveB){
    free(deriveB);
}

Vtable DeriveBVtable={
    DeriveBFun,
    DeriveBDestructure
};
DeriveB* DeriveBStructure(char v){
    DeriveB* tmp= (DeriveB*)malloc(sizeof(DeriveB));

    tmp->vprt=&DeriveBVtable;

    tmp->data=v;

    return tmp;
}



int main(){
 
    Base* da=(Base*)DeriveAStructure(1);
    Base* db=(Base*)DeriveBStructure('2');

    da->vprt->fun(da);
    db->vprt->fun(db);

    da->vprt->Destructure(da);
    db->vprt->Destructure(db);


    return 0;
}

posted @ 2023-03-14 16:22  _comet  阅读(31)  评论(0编辑  收藏  举报