C++之绝不重新定义继承而来的non-virtual函数(36)---《Effective C++》

条款36:绝不重新定义继承而来的non-virtual函数

这篇博客我们主要讲解一下为什么派生类Derived不能重新定义父类Base中的non-virtual函数,在分析之前,请大家分析一下如下代码:

#include <iostream>
#include <string>
using namespace std;
class Base{
public:
    Base(int x) :x(x){

    }
    void show(){
        cout << "Base::show()" << endl;
    }
private:
    int x;
};
class Derived :public Base{
public:
    Derived(int x) :Base(x){

    }
    void show(){
        cout << "Derived::show()" << endl;
    }
};

int main(){
    Derived derived(10);
    Base* base = &derived;
    Derived* deriv = &derived;
    base->show();
    deriv->show();
    delete base;
    return 0;
}

运行结果:
这里写图片描述
可以看到,并没有向virtual函数那样表现良好,到底是什么问题呢?non-virtual函数Base::show和Derived::show都是静态绑定(statically bound)的,这样意味着,由于base被声明为Base*,通过base调用non-virtual函数show,将永远只能获得Base所定义的版本,即使base指针实际指向的是Base的派生类Derived的对象那个,然鹅并没有什么用,因为静态绑定呀!!!
另一方面,virtual函数执行动态绑定,所以它可以“智能”调用我们想要的函数。
如果你正在编写class Derived并重新定义继承自class B的non-virtual函数show,Derived对象对象坑你会表现出精神分裂的行为,即使References也会出现这种问题!因为“静态绑定”呀!PS:
静态绑定—引用版

#include <iostream>
#include <string>
using namespace std;
class Base{
public:
    Base(int x) :x(x){

    }
    void show(){
        cout << "Base::show()" << endl;
    }
private:
    int x;
};
class Derived :public Base{
public:
    Derived(int x) :Base(x){

    }
    void show(){
        cout << "Derived::show()" << endl;
    }
};

int main(){
    Derived derived(10);
    Base base = derived;
    base.show();
    return 0;
}

运行结果:
这里写图片描述

总结:
1)适用于Base对象的每一件事,一定适用于Derived对象,因为每个Derived对象那个都是一个Base对象;
2)Base的子类Derived class一定会继承show的接口和实现,因为show是Base的一个non-virtual函数;
3)绝对不要重新定义继承而来的non-virtual函数。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值