C语言实现继承多态

    科技2026-04-15  3

    #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(struct cat *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

    Processed: 0.017, SQL: 9