C++中用成員函數指標類比多態

來源:互聯網
上載者:User

標籤:

1.成員函數指標的用法
 1 #include <iostream> 2 using namespace std; 3 class base 4 { 5 public: 6    int test(int lhs,int rhs) 7     { 8         cout<<"base test"<<endl; 9         return 1;10     }11 };12 class derived:public base13 {14 public:15     int test(int lhs,int rhs)16     {17         cout<<"derived test"<<endl;18         return 2;19     }20 };21 int main()22 {23     base *p;24     derived d;25     int (base::*baseFunction)(int,int);26     int (derived::*derivedFunction)(int,int);27     //基類指標指向子類對象+基類成員函數指標調用基類成員函數28     p=&d;29     baseFunction=&base::test;30     (p->*baseFunction)(1,2);//相當於d.base::test(int,int);31     //基類指標指向子類對象+基類成員函數指標調用子類成員函數32     p=&d;33     baseFunction=(int (base::*)(int,int))&derived::test;34     (p->*baseFunction)(1,2);//相當於d.test(int,int);35     return 0;36 }

輸出

base test

derived test

2.成員函數指標類比多態
 1 #include <iostream> 2 using namespace std; 3 class base 4 { 5 public: 6     base() 7     { 8         virtualFunctionPointer=&base::test; 9     }10     ~base()11     {12         13     }14     int (base::*virtualFunctionPointer)();15 16     int test()17     {18         //判斷是否為基類執行個體,防止無限遞迴19         if(virtualFunctionPointer==&base::test)20         {21             cout<<"base"<<endl;22             return 1;23         }24         //子類對象通過基類指標調用test,多態25         else26            return (this->*virtualFunctionPointer)();27       28     }29 30 };31 class derived:public base32 {33 public:34   35     derived()36     {37         virtualFunctionPointer=(int (base::*)())&derived::test;38     }39     ~derived()40     {41         42     }43     int test()44     {45         cout<<"derived"<<endl;46         return 2;47     }48 49 };50 int main()51 {52     derived d;53     base *p=&d;54     cout<<p->test()<<endl;55     base b;56     p=&b;57     cout<<p->test()<<endl;58 59     return 0;60 }

 輸出:

derived

2

base

1

C++中用成員函數指標類比多態

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.