當在 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 指標。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP