dynamic_cast的正确用例是什么?

dynamic_cast的正确用例是什么?

问题描述:

我已经被告知很多次(并且在实践中看到自己),使用dynamic_cast通常意味着糟糕的设计,因为它可以并且应该被虚拟函数替换。

I have been told many times (and seen myself in practice) that the use of dynamic_cast often means bad design, because it can and should be replaced with virtual functions.

例如,考虑以下代码:

class Base{...};
class Derived:public Base{...};
...
Base* createSomeObject(); // Might create a Derived object
...
Base* obj = createSomeObject();
if(dynamic_cast<Derived*>(obj)){
 // do stuff in one way
}
else{
// do stuff in some other way
}

很容易看出,一个虚函数 doStuff() Base ,并在 Derived

It can be easily seen that instead of writing dynamic casts we can just add a virtual function doStuff() to Base and re-implement it in Derived.

在这种情况下,我的问题是,为什么我们在语言中有dynamic_cast?是否有一个例子,其中使用dynamic_cast是合理的?

In that case, my question is, why do we have dynamic_cast in the language at all? Is there an example in which the use of dynamic_cast is justified?


我们可以只在Base中添加一个虚函数doStuff(),并在Derived中重新实现。

It can be easily seen that instead of writing dynamic casts we can just add a virtual function doStuff() to Base and re-implement it in Derived.

YES 。这是 virtual 的函数。

YES. That is what virtual functions are for.

class Base
{
  public:
      virtual void doStuff();
};
class Derived: public Base
{
  public:
      virtual void doStuff(); //override base implementation
};

Base* createSomeObject(); // Might create a Derived object

Base* obj = createSomeObject();
obj->doStuff(); //might call Base::doStuff() or Derived::doStuff(), depending on the dynamic type of obj;


$ b dynamic_cast ?

使用 dynamic_cast 通常表示使用通用接口无法达到目标(即 virtual function),因此你需要将它强制转换为精确类型,以便调用类型base /派生类的特定成员函数。

Use of dynamic_cast usually indicates that you cannot acheive your goal using common interface (i.e virtual functions), hence you need to cast it to exact type, so as to call the specific member functions of type base/derived classes.