C-面向对象

继承

#include <stdio.h>
#include <stdlib.h>
typedef struct _Human{
    int age;
    int height;
    unsigned long addr_num;
    void (*eat)(struct _Human* _this);
}Human;

void h_eat(struct _Human* _this);

Human nvWa = {
    .eat = h_eat,
    .age = 0,
    .addr_num = 0,
    .height = 0
};




typedef struct Woman{
    Human hm;//父类指针一定要在第一个位置
    int id;
}Woman;
void newWoman(Woman *wm,Human hm);

void human_hello(Human* h);


int main()
{
    Woman w;
    newWoman(&w,nvWa);
    w.hm.age = 1024;
    w.hm.addr_num = 332200;
    w.hm.height = 164;

    human_hello(&w);


    w.hm.eat(&w);

    getchar();


    return 0;
}



void human_hello(Human* h){
  printf("age:%d, height: %d, addr_num: %d\n",h->age,h->height,h->addr_num);
}



void h_eat(struct _Human* _this){
    printf("human eat function\n");
}


void newWoman(Woman *wm,Human hm){
    wm->hm = hm;

}




继承和多态

#include <stdio.h>
typedef struct Inf_Motor{
    int id;
    void(*enable)(void);
}Inf_Motor;

void Jog(Inf_Motor* if_mt){
    printf("id is:%d\n",if_mt->id);
}

typedef struct HCFA_Motor{
    Inf_Motor if_mt;
}HCFA_Motor;



typedef struct ELMO_Motor{
    Inf_Motor if_mt;
}ELMO_Motor;


void HCFA_Mt_en(){
    printf("HCFA_Mt_en\n");
}

void ELMO_Mt_en(){
    printf("ELMO_Mt_en\n");
}



int main(){

    HCFA_Motor hcfaMt;
    hcfaMt.if_mt.id = 1;
    hcfaMt.if_mt.enable = HCFA_Mt_en;
    ELMO_Motor elmoMt;
    elmoMt.if_mt.id = 2;
    elmoMt.if_mt.enable = ELMO_Mt_en;

    Jog(&hcfaMt);
    Jog(&elmoMt);

    
    hcfaMt.if_mt.enable();
    elmoMt.if_mt.enable();



    return 0;
}

console:

id is:1
id is:2
HCFA_Mt_en
ELMO_Mt_en

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值