先看下面一段代碼,衍生類別沒有重新實現non-virtual函數print函數:
- #include <iostream>
- using namespace std;
- class Base
- {
- public:
- void print()
- {
- cout <<" invoked from Base" << endl;
- }
- };
-
- class Derived: public Base
- {
- public:
- //void print()//隱藏了Base::printf函數
- //{
- // cout <<" invoked from Derived" << endl;
- //}
- };
-
- int main()
- {
- Derived d;
- Base *base = &d;
- Derived *derived = &d;
- base->print();
- derived->print();
- }
運行結果:
這個結果很明顯,在此不做解釋。
但是如果衍生類別又定義了自己的函數print版本:
- #include <iostream>
- using namespace std;
- class Base
- {
- public:
- void print()
- {
- cout <<" invoked from Base" << endl;
- }
- };
-
- class Derived: public Base
- {
- public:
- void print()//隱藏了Base::printf函數
- {
- cout <<" invoked from Derived" << endl;
- }
- };
-
- int main()
- {
- Derived d;
- Base *base = &d;
- Derived *derived = &d;
- base->print();
- derived->print();
- }
輸出結果:
雖然兩個指標都是通過對象d來調用成員函數print,但是結果卻不一樣。子類Derived有自己的實現版本,隱藏了父類的print函數。
為什麼這種情況下會結果不一樣呢?
這是因為non-virtual函數都是靜態繫結。由於base被聲明為一個pointer-to-Base,通過base調用的non-virtual函數永遠是Base所定義的版本。即使base指向一個類型為Base派生之Derived的對象。
更多討論請看:http://www.dewen.org/q/5477