使用c语言实现oop的继承与多态
#include <stdio.h>
typedef struct {
int age;
void (*run)(void);
} Animal;
typedef struct {
Animal a;
int b;
void (*write)(void);
}Person;
void AnimalRun() {
printf("Animal run\n");
}
void PersonRun() {
printf("Person run\n");
}
void PersonWrite() {
printf("Person write\n");
}
Animal ConstructionAnimal(void) {
Animal a = { 0, AnimalRun };
printf("Construct Animal\n");
return a;
}
void DeconstructionAnimal(Animal* animal) {
printf("Deconstruct Animal\n");
animal->age = 0;
animal->run = NULL;
}
Person ConstructionPerson(void) {
printf("Construct Person\n");
Animal a = ConstructionAnimal(0);
Person b = { {0, PersonRun}, 0, PersonWrite };
return b;
}
void DeConstructionPerson(Person* person) {
printf("Deconstruct Person\n");
DeconstructionAnimal(&person->a);
person->b = 0;
person->write = NULL;
}
void test(Animal* p) {
p->run();
}
int main(void) {
Animal* p = NULL;
Animal a = ConstructionAnimal();
Person b = ConstructionPerson();
p = (Animal*)&b;
test(&a);
test(&b);
DeconstructionAnimal(&a);
DeConstructionPerson(&b);
system("pause");
return 0;
}
|