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

被折叠的 条评论
为什么被折叠?



