虚函数在C ++中的行为 [英] Behavior of virtual function in C++

查看:144
本文介绍了虚函数在C ++中的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,下面是两个类:

I have a question, here are two classes below:

  class Base{
      public:
          virtual void toString();       // generic implementation
  }

  class Derive : public Base{
      public:
          ( virtual ) void toString();   // specific implementation
  }

问题是:


  • 如果我想使用 Base 类型的指针执行多元主义的类在支架需要?

  • If I wanna subclass of class Derive perform polymophism using a pointer of type Base, is keyword virtual in the bracket necessary?

如果答案为否,则导出的成员函数 toString 无虚拟?

If the answer is no, what's the difference between member function toString of class Derive with and without virtual?

推荐答案

C ++ 03§10.3/ 2: / p>

C++03 §10.3/2:


如果虚拟成员函数vf是在Base类中声明的
,并且在
类Derived中声明,
间接从Base,一个成员
函数vf和同名的
相同的参数列表作为Base :: vf是
声明,然后 Derived :: vf也是
virtual(无论是否为
声明)
,它覆盖
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 Base::vf.

这篇关于虚函数在C ++中的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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