0%

C语言实现OOP

“古之欲明明德于天下者,先治其国;欲治其国者,先齐其家;欲齐其家者,先修其身;欲修其身者,先正其心;欲正其心者,先诚其意;欲诚其意者,先致其知,致知在格物。物格而后知至,知至而后意诚,意诚而后心正,心正而后身修,身修而后家齐,家齐而后国治,国治而后天下平。” – 《礼记·大学》

一、概念

  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. 参考一