#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[50];
void (*speak)(void);
} Animal;
void setName(Animal *animal, const char *name) {
strncpy(animal->name, name, sizeof(animal->name) - 1);
animal->name[sizeof(animal->name) - 1] = '\0';
}
typedef struct {
Animal base;
} Dog;
void dogSpeak(void) {
printf("Wan! Wan!\n");
}
Animal* initDog(const char *name) {
Dog *dog = (Dog*)malloc(sizeof(Dog));
setName(&dog->base, name);
dog->base.speak = dogSpeak;
return &dog->base;
}
typedef struct {
Animal base;
} Cat;
void catSpeak(void) {
printf("Miao! Miao!\n");
}
Animal* initCat(const char *name) {
Cat *cat = (Cat*)malloc(sizeof(Cat));
setName(&cat->base, name);
cat->base.speak = catSpeak;
return &cat->base;
}
void animal_speak(Animal *animal){
printf("%s :",animal->name);
animal->speak();
}
int main() {
Animal *dog = initDog("Buddy_dog");
Animal *cat = initCat("Kitty_cat");
animal_speak(dog);
animal_speak(cat);
return 0;
}
Buddy_dog :Wan! Wan!
Kitty_cat :Miao! Miao!