C ++类型转换:使用显式转换的好处? [英] C++ Type Casting: benefit of using explicit casts?

查看:140
本文介绍了C ++类型转换:使用显式转换的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用这些运算符而不是隐式转换在c ++中的好处是什么?

What are benefits of using these operators instead of implicit casting in c++?

dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression) 

为什么,在哪里,在哪种情况下我们应该使用它们?

Why, where, in which situation we should use them? And is it true that they are rarely used in OOP?

推荐答案

从你提供的转换列表中,只有一个用于假设隐式转换的感觉是static_cast。

From the list of casts you provided, the only one that makes sense to be used to supstitute an implicit cast is the static_cast.

dynamic_cast用于将超类向下转换为其子类。这不可能隐式发生,实际上并不是那么罕见的OOP。 static_cast可以在这样的转换中使用,但它是更危险的,因为它不在运行时检查,downcast是有效的。

dynamic_cast is used to downcast a superclass into its subclass. This cannot happen implicitly and is actually something that is not that rare in OOP. static_cast could be used in such a cast too, it is however more dangerous, as it does not check during run time that the downcast is valid.

最后一个转换,reinterpret_cast ,应该非常仔细地使用,因为它是最危险的。你基本上可以把任何东西转换成任何东西 - 但是你作为程序员必须确保这样的转换在语义上是有意义的,因为你基本上通过这样的转换关闭类型检查。

The last cast, reinterpret_cast, should be used very carefully as it is the most dangerous of all. You can essentially cast anything into anything with that - but you as the programmer will have to make sure that such cast makes sense semantically, as you essentially turn off type checking by doing such cast.

这篇关于C ++类型转换:使用显式转换的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆