派生类中的方法在引用的类中没有* virtual *关键字的情况下被执行 [英] method in the derived class got executed without a *virtual* keyword in the referred class

查看:58
本文介绍了派生类中的方法在引用的类中没有* virtual *关键字的情况下被执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class vehicle
{
public:
    virtual void drive()
    {
        cout<<"in vehicle drive"<<endl;
    }
};
class bus:public vehicle
{
public:
    void drive()
    {
        cout<<"in bus drive"<<endl;
    }
};
class supervehicle:public bus
{
public:
    void drive()
    {
        cout<<"in supervehicle"<<endl;
    }
};


int main()
{
    bus *b;
    b=new supervehicle();
    b->drive();
    return 0;
}

我希望输出为在公交车上" ,但输出为在超级车上" .如果 virtual 关键字与总线类中的 drive 方法相关联,则确保输出应为在总线驱动器中.我知道我们已经继承了车辆类,但是仍然只为公交车类创建了指针.有人可以帮我一下,为什么 vehicle 类中的 virtual 关键字会影响 bus 类的方法,以及我在哪里遗漏了要点?>

I expected the ouput as "in bus drive", but the output is "in supervehicle". If the virtual keyword is associated with the drive method in the bus class then for sure the output should be in bus drive. I know that we have inherited the vehicle class, but still we have created the pointer for bus class only. Could somebody please help me why the virtual keyword in the vehicle class is affecting the bus class's method and where am I missing the point?

推荐答案

virtual 关键字是一个说明符,表示应通过动态调度调用该函数.它不需要在每个派生类中重复;一旦成员函数是虚拟的,则在每个派生类中都是虚拟的.

The virtual keyword is a specifier that signifies the function should be called via dynamic dispatch. It doesn't require repeating in each derived class; once a member function is virtual, it is virtual in each derived class.

通过动态调度调用的是最派生类中的版本,该版本将其覆盖.因此,在您的情况下,由 b 指向的对象的动态类型为 supervehicle ,因此调用的函数为 supervehicle :: drive ,并且不是 bus :: drive .

And the one called via dynamic dispatch is the version from the most derived class that overrides it. So in your case, the dynamic type of the object pointed to by b is supervehicle, so the function called is supervehicle::drive, and not bus::drive.

2011年C ++标准修订版中的一个相关说明符是 override .您应该在覆盖的函数上使用它,以使编译器知道您正在尝试覆盖虚拟函数.如果您在函数原型中犯了一个错误,编译器将发出诊断信息.

A related specifier, that came in the 2011 revision of the C++ standard is override. You should use it on overridden functions to let the compiler know you are attempting to override a virtual function. If you made a mistake in the functions prototype, the compiler will issue a diagnostic.

这篇关于派生类中的方法在引用的类中没有* virtual *关键字的情况下被执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆