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

本文转载自: http://www.cnblogs.com/waytofall/archive/2012/07/09/2583645.html 作者:waytofall 转载请注明该声明。

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

#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


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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值