小猫与小狗

本文通过C语言实现了一个简单的面向对象编程模拟,定义了动物、猫和狗三个类,并实现了各自的叫声行为。通过继承机制,猫和狗继承了动物的基础属性,并各自实现了特有的叫声功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

dog.h

注:狗的结构体是继承了动物的结构体,当然也在这里定义了狗的动作(叫)这个类型

#ifndef DOG_H__
#define DOG_H__

#include 
"animal.h"

typedef 
struct dog_t Cdog ;

struct dog_t{
    Canimal super;
}
;

typedef 
struct{
    
void (* bark)(Cdog *this);
}
dog_vmt;

void dog_Init(Cdog* this);
void dog_Bark(Cdog* this);

#endif

 

dog.c

 狗叫的实体函数付值

在初始化的时候将狗的动作付给狗实体,也就是传入

#include "dog.h"
#include 
<stdio.h>

static const dog_vmt vmt = {dog_Bark};

void dog_Init(Cdog* this){
    animal_Init(
this);
    
this->super.vmt =  (const animal_VMT*)&vmt;
}


void dog_Bark(Cdog* this){
//    fprinf(stdout, "wangwang ");
}

 

cat.h

 

#ifndef CAT_H__
#define CAT_H__

#include 
"animal.h"

typedef 
struct cat_t Ccat;

typedef 
struct cat_t{
    Canimal super;
}
;

typedef 
struct {
    
void (*bark)(Ccat* this);
}
cat_vmt;

void cat_Init(Ccat* this);
void cat_Bark(Ccat* this);

#endif

 

cat.c

 

#include "cat.h"
#include 
<stdio.h>

static const cat_vmt vmt = { cat_Bark };

void cat_Init(Ccat* this){
    animal_Init(
this);
    
this->super.vmt = (const animal_VMT*)&vmt;
}


void cat_Bark(Ccat* this){
    fprintf(stdout, 
"miaomiao ");
}

 

animal.h

 

#ifndef ANIMAL_H__
#define ANIMAL_H__

typedef 
struct animal_t Canimal;

typedef 
struct {
    
void (*bark)(Canimal* this);
}
animal_VMT;

struct animal_t{
    animal_VMT
* vmt;
}
;

void animal_Init(Canimal* this);
void animal_Bark(Canimal* this);

#define animal_Bark(this)
    (((Canimal
*)(this))->vmt->bark((Canimal*)this))

#endif

 

animal.c

 

#include "animal.h"

void animal_Init(Canimal* this){



}

 

main.c

 

#include "dog.h"
#include 
"cat.h"
#include 
"animal.h"


int main(){
    Ccat neko;
    Cdog yinu;

    dog_Init((Canimal
*)&yinu);
    cat_Init((Canimal
*)&neko);

    animal_Bark((Canimal
*)&neko);
    animal_Bark((Canimal
*)&yinu);

    
return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的横打

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值