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.
最满意答案
对于指针,这是一个简单的空检查:
A* a = new A(); B* b = dynamic_cast<B*>(a); if (b == NULL) { // Cast failed }对于参考,你可以看到:
try { SomeType &item = dynamic_cast<SomeType&>(obj); } catch(const std::bad_cast& e) { // Cast failed }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 }更多推荐
发布评论