小猫与小狗

来源:互联网 发布:学生空间七天网络登录 编辑:程序博客网 时间:2024/04/26 19:19

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;

}
原创粉丝点击