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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// ============================================
// C 语言实现完整的虚函数表机制
// ============================================
// 前向声明
typedef struct Animal Animal;
typedef struct Dog Dog;
typedef struct Cat Cat;
// ========== 虚函数表定义 ==========
typedef struct {
void (*speak)(Animal* this);
void (*eat)(Animal* this, const char* food);
void (*destroy)(Animal* this);
const char* type_name;
} AnimalVTable;
// ========== 基类 Animal ==========
struct Animal {
const AnimalVTable* vptr;
char* name;
int age;
};
// Animal 的虚函数实现
static void Animal_speak_impl(Animal* this) {
printf("[%s] *generic animal sound*\n", this->name);
}
static void Animal_eat_impl(Animal* this, const char* food) {
printf("[%s] eats %s\n", this->name, food);
}
static void Animal_destroy_impl(Animal* this) {
printf("[Animal] destroying %s\n", this->name);
free(this->name);
free(this);
}
// Animal 的 vtable
static const AnimalVTable Animal_vtable = {
.speak = Animal_speak_impl,
.eat = Animal_eat_impl,
.destroy = Animal_destroy_impl,
.type_name = "Animal"
};
// Animal 构造函数
Animal* Animal_create(const char* name, int age) {
Animal* this = malloc(sizeof(Animal));
this->vptr = &Animal_vtable;
this->name = strdup(name);
this->age = age;
return this;
}
// ========== 派生类 Dog ==========
struct Dog {
Animal base; // 基类子对象(必须放在开头)
char* breed;
};
// Dog 的虚函数实现
static void Dog_speak_impl(Animal* this) {
Dog* dog = (Dog*)this; // 向下转型
printf("[%s the %s] WOOF WOOF! 🐕\n", dog->base.name, dog->breed);
}
static void Dog_eat_impl(Animal* this, const char* food) {
Dog* dog = (Dog*)this;
printf("[%s] devours %s with enthusiasm!\n", dog->base.name, food);
}
static void Dog_destroy_impl(Animal* this) {
Dog* dog = (Dog*)this;
printf("[Dog] destroying %s\n", dog->base.name);
free(dog->breed);
free(dog->base.name);
free(dog);
}
// Dog 的 vtable
static const AnimalVTable Dog_vtable = {
.speak = Dog_speak_impl,
.eat = Dog_eat_impl,
.destroy = Dog_destroy_impl,
.type_name = "Dog"
};
// Dog 构造函数
Dog* Dog_create(const char* name, int age, const char* breed) {
Dog* this = malloc(sizeof(Dog));
this->base.vptr = &Dog_vtable;
this->base.name = strdup(name);
this->base.age = age;
this->breed = strdup(breed);
return this;
}
// ========== 派生类 Cat ==========
struct Cat {
Animal base;
int lives_remaining;
};
static void Cat_speak_impl(Animal* this) {
Cat* cat = (Cat*)this;
printf("[%s] Meow~ 😺 (lives: %d)\n", cat->base.name, cat->lives_remaining);
}
static void Cat_eat_impl(Animal* this, const char* food) {
Cat* cat = (Cat*)this;
printf("[%s] elegantly nibbles %s\n", cat->base.name, food);
}
static void Cat_destroy_impl(Animal* this) {
Cat* cat = (Cat*)this;
printf("[Cat] destroying %s\n", cat->base.name);
free(cat->base.name);
free(cat);
}
static const AnimalVTable Cat_vtable = {
.speak = Cat_speak_impl,
.eat = Cat_eat_impl,
.destroy = Cat_destroy_impl,
.type_name = "Cat"
};
Cat* Cat_create(const char* name, int age, int lives) {
Cat* this = malloc(sizeof(Cat));
this->base.vptr = &Cat_vtable;
this->base.name = strdup(name);
this->base.age = age;
this->lives_remaining = lives;
return this;
}
// ========== 多态接口函数 ==========
// 这些函数展示了 C++ 编译器如何实现虚函数调用
void animal_speak(Animal* animal) {
animal->vptr->speak(animal);
}
void animal_eat(Animal* animal, const char* food) {
animal->vptr->eat(animal, food);
}
void animal_destroy(Animal* animal) {
animal->vptr->destroy(animal); // 虚析构!
}
const char* animal_type(Animal* animal) {
return animal->vptr->type_name;
}
// ========== 主程序 ==========
int main() {
printf("╔══════════════════════════════════════════╗\n");
printf("║ C 语言实现 C++ 虚函数表机制演示 ║\n");
printf("╚══════════════════════════════════════════╝\n\n");
// 创建对象(每个对象的 vptr 指向正确的 vtable)
Dog* dog = Dog_create("Buddy", 3, "Golden Retriever");
Cat* cat = Cat_create("Whiskers", 5, 9);
Animal* animal = Animal_create("Generic", 10);
// 存储在基类指针数组中
Animal* zoo[] = {
(Animal*)dog,
(Animal*)cat,
animal
};
int count = sizeof(zoo) / sizeof(zoo[0]);
// 多态调用
printf("=== 多态调用 speak() ===\n");
for (int i = 0; i < count; i++) {
printf("Type: %-8s | ", animal_type(zoo[i]));
animal_speak(zoo[i]);
}
printf("\n=== 多态调用 eat() ===\n");
for (int i = 0; i < count; i++) {
animal_eat(zoo[i], "food");
}
// 展示 vtable 的工作原理
printf("\n=== vtable 内部机制 ===\n");
printf("dog->vptr = %p\n", (void*)dog->base.vptr);
printf("cat->vptr = %p\n", (void*)cat->base.vptr);
printf("animal->vptr = %p\n", (void*)animal->vptr);
printf("\nvptr 不同,所以调用相同的函数会执行不同的代码!\n");
// 虚析构
printf("\n=== 虚析构函数 ===\n");
for (int i = 0; i < count; i++) {
animal_destroy(zoo[i]);
}
return 0;
}
|