在写代码时遇到了以下类似情况:
#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
可见在还是父类的方法被调用了。这可能是非虚函数在编译器时期就已经确定调用函数地址的原因吧。