C++中如何實現虛擬函式?
C++ 中的虛擬函式用於建立基類指標的列表並呼叫衍生類的方法,而無需知道具體衍生類的物件。虛擬函式在執行時被延遲解析。
以下是 C++ 程式中虛擬函式的實現 -
示例
#include <iostream>
using namespace std;
class B {
public:
virtual void s() { //virtual function
cout<<" In Base \n";
}
};
class D: public B {
public:
void s() {
cout<<"In Derived \n";
}
};
int main(void) {
D d; // An object of class D
B *b= &d; // A pointer variable of type B* pointing to d
b->s(); // prints"D::s() called"
return 0;
}輸出
In Derived
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP