首页 > 其他分享 >纯C实现多态

纯C实现多态

时间:2023-03-14 16:34:13浏览次数:49  
标签:tmp Vtable 实现 DeriveA void 多态 vprt DeriveB

用 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;
}

标签:tmp,Vtable,实现,DeriveA,void,多态,vprt,DeriveB
From: https://www.cnblogs.com/komet/p/17215373.html

相关文章