純c結構體與c++結構體的理解,c結構體理解

來源:互聯網
上載者:User

純c結構體與c++結構體的理解,c結構體理解

//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;}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.