关于C++中子类调用父类方法的一个问题

在写代码时遇到了以下类似情况:

#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


可见在还是父类的方法被调用了。这可能是非虚函数在编译器时期就已经确定调用函数地址的原因吧。

posted @ 2012-07-09 20:43  waytofall  阅读(37305)  评论(3编辑  收藏  举报