Virtual 关键字,派生类重写父类的方法

定义C++中 虚函数的关键字
在使用virtual之前,C++对成员函数使用静态联编,而使用virtual,并且在调用函数时是通过指针或引用调用,C++则对成员函数进行动态编联(引用百科)。
 
我们通常用virtual 关键字来修饰类方法,让其派生类或子类有重写该方法。我们来看个例子:
#include <iostream>
class BaseImp{
public:
    BaseImp(){
    }
    virtual  ~BaseImp(){
    }
    virtual void OnPress() const=0;
};

class DerivedA:public BaseImp{
public:
    DerivedA(){
    }
    ~DerivedA(){
    }
    void OnPress() const{
        std::cout<<"Derived_______A"<<std::endl;
    }
};

class DerivedB:public DerivedA{
public:
    DerivedB(){
   }
    ~DerivedB(){
    }
    void OnPress() const{
        std::cout<<"Derived______B"<<std::endl;
    }
};

int main(){
    BaseImp *pNewImp = new DerivedB(); //
    pNewImp->OnPress();
    if( pNewImp != 0){
        delete pNewImp;
        pNewImp=0;
    }

    DerivedA *pNewBase = new DerivedB();
    pNewBase->OnPress();
    if(pNewBase != 0){
        delete pNewBase;
        pNewBase = 0;
    }
    return 0;
}
输出的结果:
Derived______B
Derived______B
 
为什么是这样的?好,我现在来分析一下这个结果:
   BaseImp *pNewImp = new DerivedB(); // 
    pNewImp->OnPress(); //因为BaseImp 中的方法OnPress 是一个纯虚函数(virtual),BaseImp的OnPress 方法现在能够被重写。所以会输出:
   
   
erived______B

分析第二个结果:
    DerivedA *pNewBase = new DerivedB();
    pNewBase->OnPress(); //我们一下,诶,DerivedA中的OnPress 没有virtual,怎么也会调用DerivedB中的OnPress呢,好,现在分析,因为
在接口BaseImp中,OnPress是用virtual 修饰的,而DerivedA中的OnPress是从该接口所继承过来的,这说明了,DerivedA中的OnPress能够被重写,也就是说也有virtual 关键字修饰,此时DerivedB继承DerivedA,那么DerivedB的OnPress也能够被重写。
所以:
DerivedA *pNewBase = new DerivedB(); //采用多态
pNewBase->OnPress();  //调用Derived 中的 OnPress() 方法;
 
总结:
在接口中用virtual 修饰的方法,在其派生中,该方法能够被重写。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值