當在 C++ 中的非虛擬函式內呼叫虛擬函式時會發生什麼


在本部分,我們將討論 C++ 中虛擬類的趣聞。我們將先看兩種情況,然後分析事實。

  • 首先,在不使用任何虛擬函式的情況下執行程式。

  • 然後在非虛擬函式下使用任何虛擬函式執行程式。

示例

讓我們看看以下實現,以便更好地理解 −

 現場演示

#include <iostream>
using namespace std;
class BaseClass {
public:
   void display(){
      cout << "Print function from the base class" << endl;
   }
   void call_disp(){
      cout << "Calling display() from derived" << endl;
      this -> display();
   }
};
class DerivedClass: public BaseClass {
public:
   void display() {
      cout << "Print function from the derived class" << endl;
   }
   void call_disp() {
      cout << "Calling display() from derived" << endl ;
      this -> display();
   }
};
int main() {
   BaseClass *bp = new DerivedClass;
   bp->call_disp();
}

輸出

Calling display() from base class
Print function from the base class

從輸出中,我們可以理解,即使在非虛擬函式內呼叫虛擬函式時,多型行為仍然有效。呼叫哪個函式是在執行時透過應用 vptr 和 vtable 決定的。

  • vtable - 這是每個類維護的函式指標表。

  • vptr - 這是每個物件例項維護的 vtable 指標。

更新日期:2020 年 8 月 27 日

273 次瀏覽

開啟你的 職業之路

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.