casting in C++
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了casting in C++相关的知识,希望对你有一定的参考价值。
这是2013年写的一篇旧文,放在gegahost.net上面 http://raison.gegahost.net/?p=39
February 20, 2013
casting in C++
(original work by Peixu Zhu)
Unlike in C language, C++ language offers richer casting features, however, at the same time, it also brings complexity.
Keep in mind that in C++, casting may return a different address rather than the original one !
1. static_cast
- mainly focus on syntax checking at compile time, it can be used to cast a base class into a derived class.
- if it fails, the compiler will give error information.
- in case of casting from a class with multiple parent class, it may return an address offset to the sourcing address. However, casting to void* will not change the address.
2. dynamic_cast
- when it fails, it will return NULL value at run time.
- in case of casting from a class with multiple parent class, it may return an address offset to the sourcing address. However, casting to void* will not change the address.
3. reinterpret_cast
- will not change returned pointers.
- the target must have enough size to accept the source value.
4. casting classes with multiple parent classes
- for force casting/static_cast/dynamic_cast, if the casted class has more than one parent classes, the result may be not the original address, but an address having an offset to the original address. However, though the resulted address is different to the original address, comparative operator will restore the original address temporary, in case of compare to the pointer of original class. That is, the compiler will make both pointer to be the same class type in memory layout.
- However, if the pointer is casted to void*, it will not change the sourcing address.
5. internal of static_cast/dynamic a derived class which has multiple parent classes into a base class:
- get the address of the derived instance.
- if the address is zero, return it.
- if the address is non-zero, compiler will return an address with an offset to the instance address.
6. `==’ operator on two pointers of which one is subobject of another one.
- the compiler check whether the subobject one is non-zero, if it is non-zero, promote it like another one, by changing it’s address temporarily with an offset.
- when the two pointers are compared, compiler will temporary `upgrade’ the subobject to same grade class, then perform the comparison, and if the pointer is NULL, the upgrade is not necessary and then omitted.
以上是关于casting in C++的主要内容,如果未能解决你的问题,请参考以下文章
hive cast( as integer)报错 in primitive type specification
hive cast( as integer)报错 in primitive type specification
UnhandledPromiseRejectionWarning: CastError: Cast to string failed for value in mongoose
Aggressive cows (USACO 2005 February Gold) (二分查找)
[C/C++]_[初级]_[static_cast,reinterpret_cast,dynimic_cast的使用场景和区别]