如何使用dynamic_cast运算符识别失败的强制转换? [英] How to identify failed casts using dynamic_cast operator?
问题描述
Scott Meyer
在他的书Effective C++
中说,dynamic_cast
用于执行向下或跨继承层次结构的安全强制转换.也就是说,您可以使用dynamic_cast将指针或对基类对象的引用转换为对派生或同级基类对象的指针或引用,从而可以确定转换是否成功.
Scott Meyer
in his book Effective C++
says dynamic_cast
is used to perform safe casts down or across an inheritance hierarchy. That is, you use dynamic_cast to cast pointers or references to base class objects into pointers or references to derived or sibling base class objects in such a way that you can determine whether the casts succeeded.
失败的强制转换由空指针(强制转换指针)或异常(强制转换引用)指示.
Failed casts are indicated by a null pointer (when casting pointers) or an exception (when casting references).
我想得到两个代码段,这些代码段显示了在强制转换指针和强制转换引用的情况下失败的强制转换.
I would like to get two code snippet showing the failed cast in the case of casting pointer and casting reference can be indicated.
推荐答案
对于指针,这是一个简单的null检查:
For pointers, it's a simple null check:
A* a = new A();
B* b = dynamic_cast<B*>(a);
if (b == NULL)
{
// Cast failed
}
对于参考,您可以捕获:
For references, you can catch:
try {
SomeType &item = dynamic_cast<SomeType&>(obj);
}
catch(const std::bad_cast& e) {
// Cast failed
}
这篇关于如何使用dynamic_cast运算符识别失败的强制转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!