在寫代碼時遇到了以下類似情況:
#include <iostream> #include <string> using namespace std; class A { public: void func1(string prefix) { cout << prefix << "A::func1" << endl; } void func2(string prefix) { cout << prefix << "A::func2" << endl; func1(prefix + " "); } void func3(string prefix) { cout << prefix << "A::func3" << endl; } }; class B: public A { public: void func1(string prefix) { cout << prefix << "B::func1" << endl; } void func3(string prefix) { cout << prefix << "B::func3" << endl; A::func3(prefix + " ");
func1(prefix + " "); func2(prefix + " "); } }; int main() { B b; b.func3(""); }
情況是,如果子類中的函數調用了父類的方法,而這個父類的方法調用了一個方法,這個方法同時在子類和父類中都有定義。
輸出結果為:
B::func3
A::func3
B::func1
A::func2
A::func1
可見在還是父類的方法被調用了。這可能是非虛函數在編譯器時期就已經確定調用函數地址的原因吧。