为什么dynamic_cast在C++中被认为是不好的做法

本文关键字:认为是 dynamic cast C++ 为什么 | 更新日期: 2023-09-27 18:00:19

我知道已经有很多问题了,但我仍然不明白。举个例子:

class Projectile
{
   public:
    virtual void OnCollision(Projectile& other);
   private:
    Vector position;
    Vector velocity;
};
class Bullet : Projectile
{
    // We may want to execute different code based on the type of projectile
    // "other" is.
    void OnCollision(Projectile& other) override;
};
class Rocket : Projectile
{
    // If other is a bullet, we might want the rocket to survive the collision,
    // otherwise if it's a rocket, we may want both to explode.
    void OnCollision(Projectile& other) override;
};

我不明白没有dynamic_cast怎么能完成这个例子。我们不能仅仅依赖多态接口,因为在这种情况下,它只会为我们提供关于一个对象的信息。有没有一种方法可以在没有dynamic_cast的情况下做到这一点?

另外,为什么在C#中动态强制转换不被认为是一种糟糕的做法呢?它们在整个事件处理程序和非通用容器中一直使用。在C#中可以做的很多事情都依赖于强制转换。

为什么dynamic_cast在C++中被认为是不好的做法

在这个特定的例子中,我会添加一个受保护的方法:

protected:
   virtual int getKickassNess() = 0;
// Bullet:
   int getKickassNess() override { return 10; }
// Rocket:
   int getKickassNess() override { return 9001; }  // over 9000!
void Bullet::OnCollision(Projectile& other)
{
   if (other.getKickassNess() > this->getKickassNess())
      // wimp out and die
}

IMO子弹和火箭不应该知道彼此的存在。放入这些关于关系的知识通常会让事情变得困难,在这种特定的情况下,我可以想象它会导致混乱的循环包含问题。