如何使用 dynamic_cast 运算符识别失败的转换?

2023-12-02C/C++开发问题
17

本文介绍了如何使用 dynamic_cast 运算符识别失败的转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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.

推荐答案

对于指针,它是一个简单的空检查:

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 运算符识别失败的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6