在c ++当子类化为什么有时需要添加虚拟关键字覆盖函数? [英] in c++ when subclassing why sometimes need to add virtual keyword to overridden function?

查看:126
本文介绍了在c ++当子类化为什么有时需要添加虚拟关键字覆盖函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么有时在C ++示例中看到子类/继承,基类有virtual关键字,有时重写的函数也有virtual关键字,为什么有时需要添加到子类的虚拟关键字?
例如:

Why do I sometimes see in C++ examples when talking about subclassing / inheritance, the base class has virtual keyword and sometimes the overridden function has also the virtual keyword, why it's necessary to add to the subclass the virtual key word sometimes? For example:

class Base 
{
  Base(){};
  virtual void f()
     ......
  }
};

class Sub : public Base
{
  Sub(){};
  virtual void f()
     ...new impl of f() ...
  }
};


推荐答案

这不是必须的,只看到派生类定义。

It is not necessary, but it helps readability if you only see the derived class definition.

§10.3[class.virtual] / 3

§10.3 [class.virtual]/3


函数vf在类Base中声明,在类Derived中,直接或间接从Base派生,与Base :: vf具有相同名称和相同参数列表的成员函数vf被声明,则Derived :: vf也是virtual它是否被如此声明)并且它覆盖 97) Base :: vf。

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides 97) Base::vf.

97)基本上声明如果参数列表不同,该函数不会覆盖,也不一定是 virtual

Where footnote 97) basically states that if the argument list differs, the function will not override nor be necessarily virtual

这篇关于在c ++当子类化为什么有时需要添加虚拟关键字覆盖函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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