gpt4 book ai didi

c++ - dynamic_cast 什么时候返回 0 什么时候抛出异常? cpp

转载 作者:太空宇宙 更新时间:2023-11-04 15:13:55 27 4
gpt4 key购买 nike

在此链接中: http://www.cplusplus.com/doc/tutorial/typecasting/

When dynamic_cast cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- it returns a null pointer to indicate the failure.
If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_cast is thrown instead.

我无法从该文本部分理解 dinamic_cast 返回 null ptr 以及抛出异常时的确切条件是什么。

如果有人能给我看两个代码示例,其中一个返回 null ptr,另一个抛出异常,那将是非常合适的。谢谢。

最佳答案

这是区别:

DerivedClass *der = dynamic_cast<DerivedClass *>(someBaseClassPtr);

如果 someBaseClassPtr 不引用 DerivedClass 的对象,将返回 nullptr

DerivedClass& der = dynamic_cast<DerivedClass&>(someBaseClassObj);

如果 someBaseClassObj 实际上没有引用 DerivedClass 的对象,将抛出异常。

关于c++ - dynamic_cast 什么时候返回 0 什么时候抛出异常? cpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41213505/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com