0%

C语言实现OOP

众所周知,C语言是面向过程的,而C++是面向对象的,用面向过程的C语言实现面向对象,快哉!

一、概念

  1. 封装:结构体
  2. 继承:嵌套结构体
  3. 多态:函数指针

二、实战

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Animal{
void (*talk)(void *p);
char name[40];
char country[40];
int lifetime;
char flag;
};

struct Bird{
struct Animal an;
int wing;
};

struct Mamal{
struct Animal an;
int id;
};

void talkAnimal(void *Animal){
if (NULL == Animal) {
return ;
}
struct Animal *p = (struct Animal *)Animal;
printf("Animal talk!\n");
}

void talkBird(void *Bird){
if (NULL == Bird) {
return ;
}
struct Bird *p = (struct Bird *)Bird;
printf("Bird talk!\n");
}

void talkMamal(void *Mamal){
if (NULL == Mamal) {
return ;
}
struct Mamal *p = (struct Mamal *)Mamal;
printf("Mamal talk!\n");
}

void talk(void *Animal){
if(NULL == Animal)
return ;
struct Animal *p = (struct Animal *)Animal;
p->talk(Animal);
}

int main() {

struct Animal a;
struct Bird b;
struct Mamal m;

strcpy(a.name, "animal");
strcpy(a.country, "world");
a.lifetime = 10;
a.flag = 'A';

strcpy(b.an.name, "bird");
strcpy(b.an.country, "world");
b.an.lifetime = 30;
b.an.flag = 'B';
b.wing = 2;

strcpy(m.an.name, "panda");
strcpy(m.an.country, "china");
m.an.lifetime = 30;
m.an.flag = 'P';
m.id = 101;

printf("oop:\n");
printf("name:%s,country:%s,lifetime:%d,flag:%c\n", a.name, a.country, a.lifetime, a.flag);
printf("name:%s,country:%s,lifetime:%d,flag:%c\n\n", &a.name, &a.country, a.lifetime, a.flag);

printf("name:%s,country:%s,lifetime:%d,flag:%c,wing:%d\n", b.an.name, b.an.country, b.an.lifetime, b.an.flag, b.wing);
printf("name:%s,country:%s,lifetime:%d,flag:%c,wing:%d\n\n", &b.an.name, &b.an.country, b.an.lifetime, b.an.flag, b.wing);

printf("name:%s,country:%s,lifetime:%d,flag:%c,ID:%d\n", m.an.name, m.an.country, m.an.lifetime, m.an.flag, m.id);
printf("name:%s,country:%s,lifetime:%d,flag:%c,ID:%d\n\n", &m.an.name, &m.an.country, m.an.lifetime, m.an.flag, m.id);

a.talk = talkAnimal;
m.an.talk = talkMamal;
b.an.talk = talkBird;

talk(&a);
talk(&m);
talk(&b);

return 0;
}

三、参考

  1. 参考一