且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么dynamic_cast是邪恶的?在这种情况下,我应该使用dynamic_cast吗?

更新时间:2021-10-17 17:41:04

这完全是使用 dynamic_cast 的错误位置.您应该使用多态.每个 Animal 类都应该具有一个 virtual 函数,例如 process ,在这里您应该只调用 animal-> process().

This is EXACTLY the wrong place to use dynamic_cast. You should be using polymorphism. Each of the Animal classes should have a virtual function, say, process and here you should just call animal->process().

class Animal {
    virtual void Process() = 0;
}

class Cat : public Animal {
    void Process() { std::cout << " I am a tiny cat"; }
}

class Bear : public Animal {
    void Process() { std::cout << "I am a big bear"; }
}

void func(Animal * animal) {
    if (animal != nullptr) { animal->Process(); }
}

其他问题.

如果 animal Dog ,但由于错误导致 animal_type 说它是 Cat ,该怎么办?

What if animal is a Dog, but due to a bug animal_type says its a Cat?

有时需要 static_cast ,并且如果可能的话,请使用它代替 dynamic_cast .动态转换具有静态转换所没有的额外性能成本.为此,您必须确保知道传入的类型,因为 static_cast 更不安全.

There are times when static_cast is necessary, and if possible use it instead of dynamic_cast. Dynamic cast has the additional performance cost that static cast does not. For this, you need to be sure you know the type that is coming in, since static_cast is more unsafe.

至少, animal_type 应该是 Animal 的成员.