C实现简单的面向对象

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
#include <stdio.h>
#include <stdlib.h>
//Object begin>>>>>>>>>>>>
#define ObjectField \
void(*onDelete)(void*);
typedef struct Object{
ObjectField
} Object;
#define ObjectCreate(TYPE) malloc(sizeof(TYPE))
#define ObjectDelete(obj) {\
obj->onDelete(obj);\
free(obj);\
}
void ObjectOnDelete(void *obj){
printf("Object on delete\n");
}
Object* ObjectInit(Object *obj){
obj->onDelete = ObjectOnDelete;
return obj;
}
//Object end<<<<<<<<<<<<
typedef struct{
ObjectField
int age;
void(*sayHello)();
} People;
void PeopleSayHello(){
printf("Hello\n");
}
void PeopleOnDelete(void *p){
ObjectOnDelete(p);
printf("People on delete\n");
}
People* PeopleInit(People *p,int age){
ObjectInit((Object*)p);
p->age = age;
p->sayHello = PeopleSayHello;
p->onDelete = PeopleOnDelete;
return p;
}
int main(int argc, const char * argv[])
{
People *p = PeopleInit(ObjectCreate(People), 20);
p->sayHello();
ObjectDelete(p);
// printf("Hello, %d!\n",p->age);
return 0;
}