在动手写代码前,最重要的是理解如何在C语言中模拟面向对象的三大特性。
我知道的,封装、多态和继承。
在 C 语言中,封装一般用结构体来封装数据成员,用公共函数来操作数据成员,用函数指针来实现接口或者说模拟 C++ 中的虚函数。
C 语言是没有办法实现继承的,因此只能通过结构体组合和结构体嵌套的方式进行。
那么多态呢?就要理解一下结构体嵌套的地址偏移了。比如下面这个。
#include <stdio.h>
#include <string.h>
typedef struct
{
int age;
char name[20];
void (*print)(void *self);
}Animal;
typedef struct
{
Animal base;
int color;
}Dog;
void Dog_print(void *self)
{
Dog * dog_ptr = (Dog *)self;
printf("age = %d, name = %s, color = %d", dog_ptr->base.age, dog_ptr->base.name, dog_ptr->color);
}
void print(Animal * animal_ptr)
{
animal_ptr->print(animal_ptr);
}
int main()
{
Dog dog;
dog.base.age = 10;
strcpy(dog.base.name, "hei");
dog.base.print = Dog_print;
dog.color = 7;
print((Animal *)&dog);
}
@omnitrix_t: 基于你已有的代码基础,可以尝试做一个稍完整的项目来巩固