- 继承:在c语言中,内嵌结构体或内嵌指向结构体的指针,都可以看作对“继承”的模拟
- 抽象类:用来管理父类和子类的继承关系,通过分层来提高代码的复用性,抽象类需要被子类继承
- 接口:通过接口可以实现将两个不相关的类建立联系
- 多态:在子类继承父类的过程中,一个接口可以有多种实现,在不同子类中有不同的实现,通过基类指针去调用子类中的不同实现,就叫多态
c语言中的 结构体=面向对象
#include <stdio.h>
void speak(void)
{
printf("animal speaking...\n");
}
struct func_operations {
void (*fp1)(void);
void (*fp2)(void);
void (*fp3)(void);
void (*fp4)(void);
};
struct animal {
int age;
int weight;
struct func_operations fp;
};
struct cat {
struct animal* p;
struct animal ani; //内嵌结构体“继承”animal的属性和方法
char sex;
};
int main(void)
{
struct animal ani;
ani.age = 1;
ani.weight = 2;
ani.fp.fp1 = speak;
printf("%d %d\n", ani.age, ani.weight);
ani.fp.fp1();
struct cat c;
c.p = &ani; //使用结构体指针,通过地址获取变量具体的值
c.p->fp.fp1();
printf("%d %d\n", c.p->age, c.p->weight);
return 0;
}
1 2
animal speaking…
animal speaking…
1 2
c语言中的多态
面向对象和继承:file_system结构体作为基类,ext和fat变量作为子类
多态:fp是指向基类的指针,访问每个子类中同名函数(read/write)的不同实现,“模拟”了多态
#include <stdio.h>
struct file_operation
{
void (*read)(void);
void (*write)(void);
};
struct file_system {
char name[20];
struct file_operation fops;
};
void ext_read(void)
{
printf("ext read...\n");
}
void ext_write(void)
{
printf("ext write...\n");
}
void fat_read(void)
{
printf("fat read...\n");
}
void fat_write(void)
{
printf("fat write...\n");
}
int main(void)
{
struct file_system ext = { "ext3", {ext_read, ext_write} };
struct file_system fat = { "fat32", {fat_read, fat_write} };
struct file_system* fp;
fp = &ext;
fp->fops.read();
fp = &fat;
fp->fops.read();
return 0;
}
ext read…
fat read…
Linux内核设备驱动
- 父类kobject的方法kobject_add()将设备注册到系统;
- 通过调用device类的probe()完成驱动和设备的匹配及设备的suspend、shutdown等功能;
- 通过调用net_device类实现的open、xmit、stop等接口完成网络设备的打开、数据发送、数据停止发送等功能。
- USB网卡通过usb_device封装的接口可以实现USB网卡设备的插拔检测、底层数据传输等功能
对于图中的net_device结构体,我们也可以把它看作一个基类,对于每一个实例化的结构体变量,都代表一种不同的网卡,都把它们看作net_device基类的子类。每一个网卡都有各自不同的read/write实现,并保存在各个结构体变量的net_device_ops里,当一个指向net_device结构体类型的基类指针指向不同的结构体变量时,就可以分别去调用不同子类(具体的网卡设备)的读写函数,从而实现多态。