Chinaunix首页 | 论坛 | 博客
  • 博客访问: 345484
  • 博文数量: 88
  • 博客积分: 2011
  • 博客等级: 大尉
  • 技术积分: 885
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-21 14:50
文章分类

全部博文(88)

文章存档

2010年(88)

我的朋友

分类: C/C++

2010-09-11 14:28:14

#include
#include
#define MAX 10

typedef struct Animal{
void *this;
char name[MAX];
void (*shout)(struct Animal *);
}Animal;

typedef struct Swimmable{
void *this;
void (*swim)(struct Swimmable *);
}Swimmable;

typedef struct Dog{
Animal *Animal;
Swimmable *Swimmable;
}Dog;

typedef struct Cat{
Animal *Animal;
Swimmable *Swimmable;
}Cat;

void shout_Cat(Animal *cat){
printf("%s miaomiao.\n", cat->name);
}

void swim_Cat(Swimmable *cat){
printf("%s cannot swim.\n", ((Cat *)(cat->this))->Animal->name);
}

void shout_Dog(Animal *dog){
printf("%s wangwang.\n", dog->name);
}

void swim_Dog(Swimmable *dog){
printf("%s can swim.\n", ((Dog *)(dog->this))->Animal->name);
}

void visit_Animal(Animal *animal){
animal->shout(animal);
}

void visit_Swimmable(Swimmable *swimmable){
swimmable->swim(swimmable);
}

void initialize_Dog(Dog* dog, char *name){
dog->Animal = (Animal *) malloc(sizeof(Animal));
dog->Animal->this = dog;
dog->Animal->shout = shout_Dog;
strcpy(dog->Animal->name, name);
dog->Swimmable = (Swimmable *) malloc(sizeof(Swimmable));
dog->Swimmable->this = dog;
dog->Swimmable->swim = swim_Dog;
}

void initialize_Cat(Cat* cat, char *name){
cat->Animal = (Animal *) malloc(sizeof(Animal));
cat->Animal->this = cat;
cat->Animal->shout = shout_Cat;
strcpy(cat->Animal->name, name);
cat->Swimmable = (Swimmable *) malloc(sizeof(Swimmable));
cat->Swimmable->this = cat;
cat->Swimmable->swim = swim_Cat;
}

void finalize_Dog(Dog *dog){
free(dog->Animal);
free(dog->Swimmable);
}

void finalize_Cat(Cat *cat){
free(cat->Animal);
free(cat->Swimmable);
}

void main(){
Dog dog;
Cat cat;
clrscr();
initialize_Dog(&dog, "Wangcai");
initialize_Cat(&cat, "Kitty");
visit_Animal(dog.Animal);
visit_Animal(cat.Animal);
visit_Swimmable(dog.Swimmable);
visit_Swimmable(cat.Swimmable);
finalize_Dog(&dog);
finalize_Cat(&cat);
}

阅读(966) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~