C + + Explicit type conversion
(Note: This example is adapted from "C + + Primer")
For type conversions, C + + preserves the type conversion in C and provides a new type conversion method in 4. "Effective C + +" encourages us to use the new transformation approach:
First, they are easily identified in the code (whether manually identified or using tools such as grep), thus simplifying the process of finding out where the type system is being destroyed. Second, the narrower the target of each transition action, the more likely the compiler is to diagnose the wrong application. For example, if you intend to remove the constants, you will not be able to compile them unless you use the const_cast in the new transformation.
Four classes of explicit type conversions static_cast
static_castA type conversion that is used to enforce an object, but requires that the object is not a constant on the underlying (the pointer constant is the top-level constant, and the pointer points to the content constant, the underlying constant).
int21;doublestatic_cast<double>(j) / i;
static_castIt can also be used for type conversions that cannot be performed automatically by the compiler, such as:
double dval;void *p = &dval;doublestatic_cast<double*>(p);
Const_cast
const_castThe constant nature of the const object is removed, and only this type of conversion in C + + const_cast can do this. It is legal to remove the constants of an object, but writing to a constant object after removal results in undefined results .
Example:
constchar *cp;charstatic_cast<char// 错误:static_cast不能移除常量性static_cast// 正确const_cast// 错误:const_cast只能用于移除常量性,不能进行强制类型转换
Reinterpret_cast
reinterpret_castPerforms the underlying type conversion operation on the bit data, as the name implies, as a "re-interpretation".
Example:
int *ip;charreinterpret_cast<char*>(ip);
It should be noted, however, that reinterpret_cast the actual actions are closely related to the implementation of the compiler, which may produce unexpected errors and reduce the portability of the program, which is not recommended for use in this bibliography.
dynamic_cast
The conversion mode is closely related to Rtti and will be supplemented later.
Reference books
- "C + + Primer" Chinese fifth edition
- "Effective C + +" Chinese third edition
C + + Explicit type conversion