且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++类型转换:使用显式转换的好处?

更新时间:2023-02-13 08:32:00

从你提供的转换列表中,只有一个用于假设隐式转换的感觉是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.