so true

          心懷未來,開創(chuàng)未來!
          隨筆 - 160, 文章 - 0, 評論 - 40, 引用 - 0
          數(shù)據(jù)加載中……

          多態(tài)的兩種實現(xiàn)方法

          多態(tài)體現(xiàn)在父類和派生類之間,通過函數(shù)覆蓋,實現(xiàn)在運行過程中動態(tài)調(diào)用函數(shù)。
          必要條件:
          (1)父類中將該函數(shù)聲明為virtual
          (2)子類中完全一致的覆蓋父類中的函數(shù),要求返回值、函數(shù)名、參數(shù)都一致
          (3)通過指針或者借助于函數(shù)來實現(xiàn)
          方法一(利用指針):
          #include <iostream.h>
          class A
          {
          public:
           virtual void func()
           {
            cout<<"A::func()"<<endl;
           }
          }

          class B: public A
          {
          public:
           void func()
           {
            cout<<"B::func()"<<endl;
           }
          }

          void main()
          {
           A tmp=new B();//A tmp=new B;也行
           tmp->func();

           B tmp2;
           ((A *)&tmp2)->func();
          }

          方法二(利用函數(shù)):
          #include <iostream.h>
          class A
          {
          public:
           virtual void func()
           {
            cout<<"A::func()"<<endl;
           }
           void test()
           {
            func();//***//
           }
          }

          class B: public A
          {
          public:
           void func()
           {
            cout<<"B::func()"<<endl;
           }
          }

          void main()
          {
           B tmp;
           tmp.test();
          }
          對于//***//行,有很多說道,“func();”等價于“this.func()”,能否實現(xiàn)多態(tài),關(guān)鍵是看這里的this指向父類還是子類,由于this指針必須得指向某個對象,當我們用“B tmp”或者“A tmp=new B”構(gòu)造完對象tmp后,由于tmp本質(zhì)上都是一個B的對象,因此該this指針就是指向子類的。

          posted on 2008-02-23 19:28 so true 閱讀(1060) 評論(0)  編輯  收藏 所屬分類: C&C++

          主站蜘蛛池模板: 湘阴县| 韶关市| 锡林浩特市| 崇文区| 河曲县| 浦县| 清涧县| 青铜峡市| 临清市| 天门市| 亳州市| 鄢陵县| 逊克县| 固安县| 青川县| 武夷山市| 栾城县| 江孜县| 濉溪县| 藁城市| 青川县| 沽源县| 襄城县| 台北县| 北安市| 上犹县| 汝城县| 咸阳市| 七台河市| 兖州市| 遂宁市| 拉萨市| 延川县| 革吉县| 阿勒泰市| 靖远县| 鄯善县| 苗栗县| 龙川县| 绩溪县| 玉龙|