C++的函數調用默認不使用動態綁定。要觸發動態綁定,必須滿足兩個條件:
- 只有指定為虛函數的成員函數才能進行動態綁定
- 必須通過基類類型的引用或指針進行函數調用
因為每個派生類對象中都擁有基類部分,所以可以使用基類類型的指針或引用來引用派生類對象
示例
#include <iostream> #include <string> using namespace std; struct base { base(string str = "Base") : basename(str) {} virtual void print() { cout << basename << endl; } private: string basename; }; struct derived : public base { derived(string str = "Derived") : derivedname(str) {} void print() { cout << derivedname << endl; } private: string derivedname; }; int main() { base b; derived d; cout << "b.print(), d.print()" << endl; b.print(); d.print(); base *pb = &b; base *pd = &d; cout << "pb->print(), pd->print()" << endl; pb->print(); pd->print(); base &yb = b; base &yd = d; cout << "yb.print(), yd.print()" << endl; yb.print(); yd.print(); }
結果
分析
可以看出基類類型的指針或引用來引用派生類對象時,調用的是重定義的虛函數。要想覆蓋虛函數機制,調用基函數的版本,可以使用強制措施。例:
代碼
#include <iostream> #include <string> using namespace std; struct base { base(string str = "Base") : basename(str) {} virtual void print() { cout << basename << endl; } private: string basename; }; struct derived : public base { derived(string str = "Derived") : derivedname(str) {} void print() { cout << derivedname << endl; } private: string derivedname; }; int main() { base b; derived d; cout << "b.print(), d.print()" << endl; b.print(); d.base::print(); base *pb = &b; base *pd = &d; cout << "pb->print(), pd->print()" << endl; pb->print(); pd->base::print(); base &yb = b; base &yd = d; cout << "yb.print(), yd.print()" << endl; yb.print(); yd.base::print(); }
結果