C語言中的面向?qū)ο?1)-類模擬和多態(tài),繼承

字號:

在面向?qū)ο蟮恼Z言里面,出現(xiàn)了類的概念。這是編程思想的一種進化。所謂類:是對特定數(shù)據(jù)的特定操作的集合體。所以說類包含了兩個范疇:數(shù)據(jù)和操作。而C語言中的struct僅僅是數(shù)據(jù)的集合。(liyuming1978@163.com)
    1.實例:下面先從一個小例子看起
    #ifndef C_Class
     #define C_Class struct
    #endif
    C_Class A {
     C_Class A *A_this;
     void (*Foo)(C_Class A *A_this);
     int a;
     int b;
    };
    C_Class B{ //B繼承了A
     C_Class B *B_this; //順序很重要
     void (*Foo)(C_Class B *Bthis); //虛函數(shù)
     int a;
     int b;
     int c;
    };
    void B_F2(C_Class B *Bthis)
    {
     printf("It is B_Fun\n");
    }
    void A_Foo(C_Class A *Athis)
    {
     printf("It is A.a=%d\n",Athis->a);//或者這里
    // exit(1);
    // printf("純虛 不允許執(zhí)行\(zhòng)n");//或者這里
    }
    void B_Foo(C_Class B *Bthis)
    {
     printf("It is B.c=%d\n",Bthis->c);
    }
    void A_Creat(struct A* p)
    {
     p->Foo=A_Foo;
     p->a=1;
     p->b=2;
     p->A_this=p;
    }
    void B_Creat(struct B* p)
    {
     p->Foo=B_Foo;
     p->a=11;
     p->b=12;
     p->c=13;
     p->B_this=p;
    }
    int main(int argc, char* argv[])
    {
     C_Class A *ma,a;
     C_Class B *mb,b;
     A_Creat(&a);//實例化
     B_Creat(&b);
     mb=&b;
     ma=&a;
     ma=(C_Class A*)mb;//引入多態(tài)指針
     printf("%d\n",ma->a);//可惜的就是 函數(shù)變量沒有private
     ma->Foo(ma);//多態(tài)
     a.Foo(&a);//不是多態(tài)了
     B_F2(&b);//成員函數(shù),因為效率問題不使用函數(shù)指針
     return 0;
    }
    輸出結果:
    11
    It is B.c=13
    It is A.a=1
    It is B_Fun