C++各类型转换的总结

来源:互联网 发布:js中on和bind的区别 编辑:程序博客网 时间:2024/06/14 16:49

dynamic_cast

dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

When a class is polymorphic, dynamic_cast performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class:
If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of typebad_cast is thrown instead.

dynamic_cast can also cast null pointers even between pointers to unrelated classes, and can also cast pointers of any type to void pointers (void*).

static_cast

static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type.

static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly

 

reinterpret_cast

reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.

It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is granted to be able to be cast back to a valid pointer.

const_cast

This type of casting manipulates the constness of an object, either to be set or to be removed

 

总结:dynamic_cast 可以由派生类转换到基类,也可由指向派生类的基类转换成派生类。

            static_cast 可以在派生类和基类中自由转换。

            reinterpret_cast类可以在任何类中自由转换。

     以上转换都是指针间的转换

 

     static_cast 还可用于非指针的各基本数据类型间的转换。

     reinterpret_cast可用于任何指针间的转换,也可用于从整数类型到指针间的转换。

 

 

原创粉丝点击