重寫、過載、隱藏
阿新 • • 發佈:2020-10-14
https://blog.csdn.net/jiangtaigong/article/details/83255471
https://blog.csdn.net/alpha_love/article/details/75222175
#include <iostream> using namespace std; class P { private: virtual void showMeImpl(); public: void showMe(); }; void P::showMeImpl() { cout << "here is the parent" << endl; } void P::showMe() { showMeImpl(); } class C : public P { private: void showMeImpl(); public: void showMe(); }; void C::showMeImpl() { cout << "here is the child" << endl; } void C::showMe() { cout << "here is the childhhhhhhhhhhhhh" << endl; } int main() { C c; P& p = c; p.showMe(); P* p2 = &c; p2->showMe(); }
基類中是否出現virtual很關鍵,無論virtual是出現在私有區域還是共有區域,只要在基類中出現,就會創建出虛擬函式表,派生類即會繼承這個虛擬函式表,實現執行時的多型
若基類中沒有出現virtual,那麼派生類繼承了父類,只能表現出靜態多型
注意virtual的位置
若virtual修飾的是showMeImpl,那麼結果為
here is the child
here is the child
若virtual修飾的是showMe,那麼結果為
here is the childhhhhhhhhhhhhh
here is the childhhhhhhhhhhhhh