Repository navigation
Expand file tree
/
Copy pathoop_in_c.c
More file actions
187 lines (161 loc) · 6.55 KB
/
Copy pathoop_in_c.c
File metadata and controls
187 lines (161 loc) · 6.55 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/*
* oop_in_c.c
* ------------------------------------------------------------
* 用纯 C 模拟 C++ 的 OOP 机制,帮助理解编译器背后到底做了什么。
*
* 演示的 C++ 概念:
* 1. class / 成员函数 -> struct + 函数指针
* 2. this 指针 -> 手动传入的 struct 指针
* 3. 构造 / 析构 -> _ctor / _dtor 函数
* 4. 继承 -> 基类 struct 嵌在派生类开头
* 5. 虚函数 / 多态 -> vtable(函数指针表) + vptr
*
* 对应的 C++ 版本:
* class Animal {
* public:
* Animal(const char* name);
* virtual ~Animal();
* virtual void speak(); // 虚函数
* void describe(); // 普通成员函数
* protected:
* const char* name;
* };
* class Dog : public Animal { ... 重写 speak() ... };
* class Cat : public Animal { ... 重写 speak() ... };
* ------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ============================================================
* 前置声明
* ============================================================ */
struct Animal;
/* ------------------------------------------------------------
* vtable:虚函数表
*
* C++ 里每个含虚函数的类都有一张这样的表。表里存的是函数指针。
* 派生类会有自己的一张表,把重写的槽位替换成自己的实现。
* ------------------------------------------------------------ */
typedef struct AnimalVTable {
void (*speak)(struct Animal* self); /* virtual void speak() */
void (*dtor) (struct Animal* self); /* virtual ~Animal() */
} AnimalVTable;
/* ------------------------------------------------------------
* 基类 Animal
*
* 关键:vptr 放在对象内存的最开头。
* C++ 编译器就是这样布局的——对象首地址处藏着一个指向 vtable 的指针。
* ------------------------------------------------------------ */
typedef struct Animal {
const AnimalVTable* vptr; /* 隐藏的虚表指针(vptr),编译器自动加的 */
const char* name; /* 数据成员 */
} Animal;
/* ---- 基类的虚函数默认实现 ---- */
static void Animal_speak(Animal* self) {
printf("[%s] 发出了某种声音\n", self->name);
}
static void Animal_dtor(Animal* self) {
printf("~Animal(): 释放 %s\n", self->name);
/* 注意:真正的 free 由调用方负责,这里只做“析构逻辑” */
}
/* ---- 基类的 vtable 实例(全局唯一,所有 Animal 对象共享) ---- */
static const AnimalVTable Animal_vtable = {
Animal_speak,
Animal_dtor
};
/* ---- 构造函数:相当于 Animal::Animal(name) ---- */
static void Animal_ctor(Animal* self, const char* name) {
self->vptr = &Animal_vtable; /* 绑定虚表,这一步 C++ 编译器隐式完成 */
self->name = name;
}
/* ---- 普通成员函数(非虚):直接静态绑定,不查表 ---- */
static void Animal_describe(Animal* self) {
printf("我是一只动物,名字叫 %s。它说:", self->name);
self->vptr->speak(self); /* 通过 vptr 调虚函数 -> 动态多态 */
}
/* ============================================================
* 派生类 Dog : public Animal
* ============================================================ */
typedef struct Dog {
Animal base; /* 基类子对象放在最前面 -> (Animal*)dog 转换才安全 */
int loyalty; /* Dog 自己新增的数据成员 */
} Dog;
/* Dog 重写的 speak() */
static void Dog_speak(Animal* self) {
/* self 实际指向一个 Dog,因为 base 在开头,可安全向下转型 */
Dog* dog = (Dog*)self;
printf("汪汪!(%s, 忠诚度=%d)\n", dog->base.name, dog->loyalty);
}
static void Dog_dtor(Animal* self) {
printf("~Dog(): 释放 %s\n", self->name);
Animal_dtor(self); /* 先派生后基类,模拟 C++ 析构调用链 */
}
/* Dog 专属的 vtable:speak 槽被替换为 Dog_speak */
static const AnimalVTable Dog_vtable = {
Dog_speak,
Dog_dtor
};
static void Dog_ctor(Dog* self, const char* name, int loyalty) {
Animal_ctor(&self->base, name); /* 先构造基类部分 */
self->base.vptr = &Dog_vtable; /* 再把 vptr 指向 Dog 的虚表 */
self->loyalty = loyalty;
}
/* ============================================================
* 派生类 Cat : public Animal
* ============================================================ */
typedef struct Cat {
Animal base;
int arrogance;
} Cat;
static void Cat_speak(Animal* self) {
Cat* cat = (Cat*)self;
printf("喵~ (%s, 傲娇值=%d)\n", cat->base.name, cat->arrogance);
}
static void Cat_dtor(Animal* self) {
printf("~Cat(): 释放 %s\n", self->name);
Animal_dtor(self);
}
static const AnimalVTable Cat_vtable = {
Cat_speak,
Cat_dtor
};
static void Cat_ctor(Cat* self, const char* name, int arrogance) {
Animal_ctor(&self->base, name);
self->base.vptr = &Cat_vtable;
self->arrogance = arrogance;
}
/* ============================================================
* main:演示多态
* ============================================================ */
int main(void) {
printf("===== 1. 构造对象 =====\n");
Dog* d = malloc(sizeof(Dog));
Cat* c = malloc(sizeof(Cat));
Dog_ctor(d, "旺财", 100);
Cat_ctor(c, "咪咪", 88);
printf("\n===== 2. 多态:用基类指针数组统一处理 =====\n");
/* C++ 里就是 Animal* zoo[] = { new Dog(...), new Cat(...) }; */
Animal* zoo[2];
zoo[0] = (Animal*)d; /* 向上转型:Dog* -> Animal*,因为 base 在开头,地址不变 */
zoo[1] = (Animal*)c;
for (int i = 0; i < 2; i++) {
/* describe 内部通过 vptr->speak 调用,运行期决定实际函数 */
Animal_describe(zoo[i]);
}
printf("\n===== 3. 虚函数 vs 普通函数 =====\n");
/* 直接调虚表:等价于 C++ 的 zoo[i]->speak() */
zoo[0]->vptr->speak(zoo[0]); /* -> Dog_speak */
zoo[1]->vptr->speak(zoo[1]); /* -> Cat_speak */
printf("\n===== 4. 析构(虚析构,走各自的 dtor 链) =====\n");
for (int i = 0; i < 2; i++) {
zoo[i]->vptr->dtor(zoo[i]); /* 虚析构:正确调到 Dog_dtor / Cat_dtor */
free(zoo[i]);
}
printf("\n===== 5. 内存布局验证 =====\n");
printf("sizeof(Animal) = %zu 字节 (vptr + name)\n", sizeof(Animal));
printf("sizeof(Dog) = %zu 字节 (Animal + loyalty)\n", sizeof(Dog));
printf("Dog 对象首地址 == 其 base(Animal) 首地址 ? %s\n",
"是(这就是向上转型安全的原因)");
return 0;
}