纯c结构体与c++结构体的理解

来源:互联网 发布:linux mysql下载64位 编辑:程序博客网 时间:2024/06/14 07:23

//main.cpp

//如果文件名是以.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

#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==%d\n",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;}

这里写图片描述

1 0
原创粉丝点击