non-virtual函數的調用

來源:互聯網
上載者:User

先看下面一段代碼,衍生類別沒有重新實現non-virtual函數print函數:

  

 
  1. #include <iostream> 
  2. using namespace std; 
  3. class Base 
  4. public: 
  5.     void print() 
  6.     { 
  7.         cout <<" invoked from Base" << endl; 
  8.     } 
  9. }; 
  10.  
  11. class Derived: public Base 
  12. public: 
  13.     //void print()//隱藏了Base::printf函數 
  14.     //{ 
  15.     //  cout <<" invoked from Derived" << endl; 
  16.     //} 
  17. }; 
  18.  
  19. int main() 
  20.     Derived d; 
  21.     Base *base = &d; 
  22.     Derived *derived = &d; 
  23.     base->print(); 
  24.     derived->print(); 
  25. }

運行結果:


這個結果很明顯,在此不做解釋。
但是如果衍生類別又定義了自己的函數print版本:

  

 
  1. #include <iostream> 
  2. using namespace std; 
  3. class Base 
  4. public: 
  5.     void print() 
  6.     { 
  7.         cout <<" invoked from Base" << endl; 
  8.     } 
  9. }; 
  10.  
  11. class Derived: public Base 
  12. public: 
  13.     void print()//隱藏了Base::printf函數 
  14.     { 
  15.         cout <<" invoked from Derived" << endl; 
  16.     } 
  17. }; 
  18.  
  19. int main() 
  20.     Derived d; 
  21.     Base *base = &d; 
  22.     Derived *derived = &d; 
  23.     base->print(); 
  24.     derived->print(); 
  25. }

輸出結果:

雖然兩個指標都是通過對象d來調用成員函數print,但是結果卻不一樣。子類Derived有自己的實現版本,隱藏了父類的print函數。
為什麼這種情況下會結果不一樣呢?
這是因為non-virtual函數都是靜態繫結。由於base被聲明為一個pointer-to-Base,通過base調用的non-virtual函數永遠是Base所定義的版本。即使base指向一個類型為Base派生之Derived的對象。

更多討論請看:http://www.dewen.org/q/5477

聯繫我們

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