dynamic_cast与在父类(C ++)中暴露虚拟函数 [英] dynamic_cast vs exposing virtual functions in parent class (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屋!