C++中函式的動態繫結
阿新 • • 發佈:2018-11-09
所謂動態繫結,其實就是介面的實現由派生類完全覆蓋。
就是說原本宣告的型別是基類B,但是呼叫函式的時候執行的卻是不同派生類(由初始化或者賦值的時候定義)D的函式。動態綁定出現的條件有兩個
- 只有虛擬函式才能進行動態繫結。
- 必須通過基類型別的引用或指標進行函式呼叫。
例子
#include <iostream> using namespace std; class Base { public: virtual void vf() { cout << "virtual function from Base " << endl; } void f() { cout << "function from Base" << endl; } }; class Derived:public Base { public: void vf() { cout << "virtual function from Derived " << endl; } void f() { cout << "function from Derived" << endl; } }; int main() { Base* b; b=new Derived(); b->vf(); b->f(); }
返回結果:
virtual function from Derived
function from Base