dynamic_cast与在父类(C ++)中暴露虚拟函数 [英] dynamic_cast vs exposing virtual functions in parent class (C++)

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

问题描述

我有一个父类base和继承自base的另一个类derived。



derived有1个方法cH1。 >

如果我这样做:

  base * b = new derived 

我想要这样做:

  b-> cH1(); 

显然我不能,有两个解决方案:




  • 在基地中声明cH1为纯虚拟。

  • 或执行以下操作:

      dynamic_cast< derived *>(b) - > cH1(); 




哪一个是更好的做法? p>

解决方案

如果 cH1 方法语义适用于 / code>,然后使它成为 base 的方法。
否则,离开 cH1 派生,并使用 dynamic_cast
我认为你的类的语义应该驱使你的选择。



例如,如果你有一个基类车辆和派生类 Car 摩托车飞机 TakeOff()的方法具有与飞机兼容的语义, Car 摩托车,因此您可能想要 TakeOff() 方法,而不是方法。


I have a parent class "base" and another class "derived" that inherits from "base".

"derived" has 1 method cH1.

if I do this:

base* b = new derived();

And I want to be able to do this:

b->cH1();

Obviously I can't and there are 2 solutions:

  • Either declare cH1 as pure virtual in base.
  • or do this:

    dynamic_cast<derived*>(b)->cH1();
    

Which one is a better practice?

解决方案

If cH1 method semantically applies to base, then make it a base's method. Else, leave cH1 to derived, and use dynamic_cast. I think the semantics of your classes should drive your choice.

For example, if you have a base class Vehicle and derived classes Car, Motorbike, and Aircraft, a method like TakeOff() has a semantics compatible with Aircraft but not with Car or Motorbike, so you may want to make TakeOff() an Aircraft method, not a Vehicle method.

这篇关于dynamic_cast与在父类(C ++)中暴露虚拟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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