Appearance
Linux中的面向对象思想:封装
实现方法
- 使用结构体
- 使用函数指针
C
struct animal
{
int age;
int weight;
void (*fp)(void);
};
可以对函数等进一步封装
C
struct func_operations
{
void (*fp1)(void);
void (*fp2)(void);
void (*fp3)(void);
void (*fp4)(void);
};
struct anmal
{
int age;
int weight;
struct func_operations fp;
};
继承
C
struct cat{
struct animal *p;
struct animal ani;
char sex;
void (*eat)(void);
};
示例
C
1 #include <stdio.h>
2
3 void speak(void)
4 {
5 printf("aniaml speaking...\n");
6 }
7
8 struct func_operations{
9 void (*fp1)(void);
10 void (*fp2)(void);
11 void (*fp3)(void);
12 void (*fp4)(void);
13 };
14
15 struct animal{
16 int age;
17 int weight;
18 struct func_operations fp;
19 };
20 struct cat{
21 struct animal *p;
22 struct animal ani;
23 char sex;
24 };
25 int main(void)
26 {
27 struct animal ani;
28 ani.age = 1;
29 ani.weight = 2;
30 ani.fp.fp1 = speak;
31 printf("%d %d\n", ani.age, ani.weight);
32 ani.fp.fp1();
33
34 struct cat c;
35 c.p = &ani;
36 c.p ->fp.fp1();
37 printf("%d %d", c.p->age, c.p->weight);
38 return 0;
39
40 }
1 2
aniaml speaking...
aniaml speaking...
1 2
实例
链表的抽象继承
- 普通链表
C
struct list_node
{
int data;
struuct *next;
struct *prev;
};
- Linux中的链表
C
struct list_head
{
struct list_head *next, *prev; //分别指向上一个和下一个链表
};
设备管理器
显示设备:Linux的文件系统/sys下的devices目录
Linux中的一个设备
C
struct kobject
{
// ...
struct list_head enter;
// ...
}
通过kset结构体进行管理:/sys目录下的不同设备分类
总线型结构
实现抽象类设备驱动然后衍生出usb驱动,网卡驱动,由实例继承
继承
- 内嵌结构体,用于差别不大的设备
- 私有指针
- 抽象类添加分层
问题
- 出现多路继承
解决方案:接口:一个类的行为方法,不允许有数据成员,多继承 ==>单继承
多态
基类中包含纯虚函数,为函数指针赋予不同的具体函数。
C
1 #include <stdio.h>
2
3 struct file_operation
4 {
5 void (*read)(void);
6 void (*write)(void);
7 };
8
9 struct file_system{
10 char name[20];
11 struct file_operation fops;
12 };
13
14 void ext_read(void)
15 {
16 printf("ext read ....\n");
17 }
18
19 void ext_write(void)
20 {
21 printf("ext write ....\n");
22 }
23
24 void fat_read(void)
25 {
26 printf("fat read ...\n");
27 }
28 void fat_write(void)
29 {
30 printf("fat write ...\n");
31 }
32 int main(void)
33 {
34 struct file_system ext = {"ext3", {ext_read, ext_write}};
35 struct file_system fat = {"ext3", {fat_read, fat_write}};
36
37 struct file_system *fp;
38 fp = &ext;
39 fp->fops.read();
40 fp = &fat;
41 fp->fops.write();
42 return 0;
43
44 }
result:
ext read ....
fat write ...