C++ 入门第 5 版:dynamic_cast

C++ primer 5th edition: dynamic_cast

我有 C++ Primer 第 5 版中的这段文字:

dynamic_cast<type*>(e)

dynamic_cast<type&>(e)

dynamic_cast<type&&>(e)

In all cases, the type of e must be either a class type that is publicly derived from the target type , a public base class of the target type , or the same as the target type . If e has one of these types, then the cast will succeed. Otherwise, the cast fails. If a dynamic_cast to a pointer type fails, the result is 0. If a dynamic_cast to a reference type fails, the operator throws an exception of type bad_cast.

谢谢。

I think the contrary he meant because if the type of e is derived from the type cast then we don't need a conversion or cast because they are implicitly convertible by inheritance

如果类型不同,则必须进行转换才能达到目标类型,无论该转换是隐式还是显式。

虽然我们确实不需要强制转换,但这并不意味着强制转换会失败。所以不,我不认为他们的意思相反。 Upcasts 通过动态转换成功,引用的文本是正确的。

But normally: the type of type must be a class type that is publicly derived from the type of e...

书上第二个条件就是这个意思:

In all cases, the type of e must be either a ..., a public base class of the target type , or ...