为什么dynamic_cast是邪恶的?在这种情况下,我应该使用dynamic_cast吗? [英] Why is dynamic_cast evil or not ? Should I use dynamic_cast in this case?
问题描述
有人说 dynamic_cast的使用通常意味着错误的设计和dynamic_cast可以由虚拟函数代替
- 为什么使用
dynamic_cast
被认为是不良设计? -
假设我具有函数名称
func(Animal * animal,int animalType)
,在func中的实现类似于:
- why is the use of
dynamic_cast
considered bad design? Suppose I have I function name
func(Animal* animal, int animalType)
, the implementation in func is like:
bool func(Animal* animal, int animalType)
{
...
/* Animal is the base class of Bear, Panda, Fish ....
dynamic_cast animal to real animals(Bear, Panda, Fish...)
according to animalType. Do some processing with this specific
type of animal, using its additional information beyond base
class Animal. */
}
在这种情况下,是否正确使用了 dynamic_cast
?
Is this case a proper use of dynamic_cast
?
推荐答案
这完全是使用 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
的成员.
这篇关于为什么dynamic_cast是邪恶的?在这种情况下,我应该使用dynamic_cast吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!