为什么dynamic_cast在C++中被认为是不好的做法
Why is dynamic_cast considered bad practice in C++?
我知道已经有很多问题了,但我仍然不明白。举个例子:
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#中可以做的很多事情都依赖于强制转换。
在这个特定的例子中,我会添加一个受保护的方法:
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子弹和火箭不应该知道彼此的存在。放入这些关于关系的知识通常会让事情变得困难,在这种特定的情况下,我可以想象它会导致混乱的循环包含问题。
相关文章:
- 为什么rand()的使用被认为是不好的
- 为什么 std::shared_ptr 被认为是"heavy"和"expensive",但 std::array "same perfprmance as plain (c-style) arrays
- 一个C头文件可以被认为是一个接口吗
- 为什么const char*和const char[]作为函数参数被认为是等价的
- 为什么12.0==11.999999999999999999被认为是真的
- 这会被认为是糟糕的编程实践吗?
- 为什么这被认为是恒定的?
- 抽象类/接口中的空方法是否被认为是一种好的做法?
- 如果我具有调用其其他实例之一的超载函数,它是否被认为是递归功能
- std::unique_ptr可以被认为是一个monad吗?
- C++ 指向类的指针和/或引用是否被认为是"movable"?
- 使用自定义宏来简化 cin 和 cout 语句等内容被认为是更好还是更差
- 使用成员函数更改对象或返回并分配它是否被认为是更好的做法?
- 我很难修复我认为是双重免费的东西
- 使用 #define 被认为是"bad practice"吗?
- 是一个被认为是不同类型的班级内部的正向声明
- 这被认为是有效的C 11还是C 14?还是GCC/Clang弄错了
- 为什么这个嵌套的 lambda 不被认为是 constexpr?
- 限制C++中允许的模板参数是否被认为是不良样式?
- 是被认为是转换为常数的变量