C语言实现多态

多态 ,顾名思义多种形态。我们知道继承是子类从父类里继承共有部分,那么抽象是就是从许多个类里面找出共有部分抽象出来,所以说抽象和继承类似与互逆的过程。通过抽象我们可以建立父类。而多态就是用一个父类中的方法,来调用子类的对象,而子类对象可以是多种形态的

#include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"

#define c_virtual             //表示虚函数

typedef struct Animal;
typedef struct Animal Animal;
typedef struct Dog;
typedef struct Dog Dog;
typedef struct Bird;
typedef struct Bird Bird;

typedef struct Animal_vtable;
typedef struct Animal_vtable Animal_vtable;

void _animal_Printf(Animal* pthis);
c_virtual void dog_Printf(Dog* pthis);
c_virtual void bird_Printf(Bird* pthis);
void _animal_Printf(Animal* pthis);

//虚函数表
typedef struct Animal_vtable {
    void (*v_printf)(Animal* pthis);
}Animal_vtable;

//定义一个动物父类 动物有名字,有体型大小
typedef struct Animal {
    Animal_vtable* _vptr;
    uint8_t name[20];
    uint8_t bodily[20];
}Animal;

//定义一个子类:狗 狗有牙齿
typedef struct Dog {
    Animal super;
    uint8_t tooth;
}Dog;

//定义一个子类:鸟 鸟有翅膀
typedef struct Bird {
    Animal super;
    uint8_t wing;
}Bird;


void Animal_Init(Animal* pthis, const char* name , const char* bodily) {
    //先初始化属性
    strcpy(pthis->name, name);
    strcpy(pthis->bodily, bodily);
    //初始化虚函数表
    static Animal_vtable animal_vtable = { _animal_Printf };
    pthis->_vptr = &_animal_Printf;
}

//定义一个虚函数
c_virtual void animal_Printf(Animal* pthis)
{
    pthis->_vptr->v_printf(pthis);
}

//虚函数实体
void _animal_Printf(Animal* pthis) {
    printf("%s %s", pthis->name, pthis->bodily);
}

void dog_Init(Dog* pthis, const char* name, const char* bodily, uint8_t tooth)
{
   //先初始化属性
    Animal_Init(&pthis->super, name, bodily);
    pthis->tooth = tooth;
    //初始化虚函数表
    static Animal_vtable dog_vtable = { dog_Printf };
    pthis->super._vptr = &dog_vtable;
}

c_virtual void dog_Printf(Dog* pthis)
{
    printf("%s %s", pthis->super.name,  pthis->super.bodily );
    printf(" %s%s牙齿 \n", pthis->super.name, pthis->tooth ? "有": "没有");

}

void Bird_Init(Bird* pthis, const char* name, const char* bodily, uint8_t wing)
{
    Animal_Init(&pthis->super, name, bodily);
    pthis->wing = wing;
    static Animal_vtable bird_vtable = { bird_Printf };
    pthis->super._vptr = &bird_vtable;
}
c_virtual void bird_Printf(Bird* pthis)
{
    printf("%s %s", pthis->super.name, pthis->super.bodily);
    printf(" %s%s牙齿 \n", pthis->super.name,pthis->wing ? "有" : "没有");
}

int main()
{
    Animal Animal;
    Animal_Init(&Animal, "动物", "各种体型");
    _animal_Printf(&Animal);
    printf("\n");

    Dog black_dog;
    dog_Init(&black_dog, "黑狗", "中等体型", true);
    //dog_Printf(&black_dog);

    Bird sparrow;
    Bird_Init(&sparrow, "麻雀", "小体型", true);
    //bird_Printf(&sparrow);

    //通过父类函数调用子类对象
    animal_Printf(&black_dog);
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值