我是靠谱客的博主 呆萌小蝴蝶,这篇文章主要介绍纯c结构体与c++结构体的理解,现在分享给大家,希望可以做个参考。

//main.cpp

复制代码
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
//如果文件名是以.cpp结尾的说明这是一个c++的源程序, //在c++的源程序中,class的作用与struct的作用一模一样, //除了他们默认的成员属性不一样除外(class 默认是私有的, //struct默认是共有的),同样struct有this指针,同样struct //可以继承,同样struct也支持c++多态的所有属性,同样struct //有虚表,下面就是我做的一个struct的虚表例子。 //记住在.cpp结尾的源文件里面,struct才与class基本一致。 #include <stdlib.h> #include <stdio.h> struct A { virtual void fun() = 0; }; struct B : public A { void fun() { printf("B::fun()n"); } }; typedef void (*PF) (); void Printf(void *arg) { PF f = PF(*(int *)arg); f(); } void test() { B b; Printf((int *)*(int *)&b); } int main() { test(); return 0; }

这里写图片描述
//main.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
#include <stdlib.h> #include <stdio.h> //因为在纯c语言中的struct与c++中的属性是不太一样的。 //首先在纯c语言的struct是不支持多态的,不可以构造, //没有this,不可以有函数,如果我们要用纯c结构体来 //模拟一个class就会很困难,下面是我粗燥的写法。 struct A; typedef void(*PF)(struct A *this);//函数指针数组。 struct vPtrNode; typedef void(*PV)(struct vPtrNode *this); struct vPtrNode { PV pf;//模拟虚表。 }; void vtrprintf(struct vPtrNode *this) { printf("vtrprintf()n"); } struct A { PF f;//因为纯c语言的结构体内部是不可以定义函数的,所以用函数指针来代替。 int a; struct vPtrNode *vptr; struct B { PF p; struct A *b;//模拟继承,使结构体B调用基类A中的函数。 }B; }; void fun1(struct A *this)//this指针的模拟。 { this->a = 100; printf("fun1():a==%dn",this->a); } int main() { struct A a; a.f = (PF)fun1;//模拟this。 a.f(&a); ////////////////// a.B.p = (PF)fun1;//模式子类函数p覆盖基类中的函数f。 a.B.p(&a); a.B.b = (struct A *)malloc(sizeof(struct A)); //这里必须开辟空间,如果不开辟空间,你给指针的指针赋值一个确定 //的函数地址会出现段错误。 a.B.b->f = (PF)fun1; a.B.b->f(&a);//模拟子类调用父亲类的函数f。 //////////////////// //因为虚表只在父类中存在。 a.vptr = (struct vPtrNode *)malloc(sizeof(struct vPtrNode)); a.vptr->pf = (PV)vtrprintf; struct vPtrNode vptr; a.vptr->pf(&vptr); return 0; }

这里写图片描述

最后

以上就是呆萌小蝴蝶最近收集整理的关于纯c结构体与c++结构体的理解的全部内容,更多相关纯c结构体与c++结构体内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(96)

评论列表共有 0 条评论

立即
投稿
返回
顶部