C語言實現繼承多型

t0tott發表於2020-10-08
#include <string.h>
#include <stdio.h>
struct animal{
        char name[20];
        void (*speak)();
};
void Animal(struct animal *this, const char *name, void(*fun)()){
        strcpy(this->name, name);
        this->speak=fun;
}
struct cat{
        struct animal base;
};
void catSpeak(){
        printf("Mmmmiao~\n");
}
void Cat(const struct animal *this){
        Animal((struct animal *)this, "cat's Name is GuaGua!!!", catSpeak);
}
int main(){
        struct cat c;
        Cat(&c);
        struct animal *p = (struct animal *)&c;
        p->speak();
        printf("%s",p->name);
}

輸出結果:

(base) ➜  POLYMORPHISMbyC ./INHERI                
Mmmmiao~
cat's Name is GuaGua!!!%  

完整來源:
https://zhuanlan.zhihu.com/p/25127633

相關文章