c ++ type of conversion

First, the implicit type conversion

int m = 3 + 45.6; //48.6000000000 48 truncates the fractional part truncated

Two, C-style explicit type conversion (cast)

// int k = 5% 3.2; compiler error 

int k = 5% (int) 3.2; // C language style casts, but requires the programmer to ensure that data can be transferred correctly
int k = 5% int (3.2); (one C language style cast in) // functional style cast
int k = 5% (int) "dddd"; // C language style casts, but the results are definitely wrong
// so C-style casts an unsafe type casting

Three, C ++ type conversion

// C ++ it supports C-style cast, but provided 4 C ++ casts were used for different purposes 

// purpose is to provide a wealth of meaning and function, better type checking mechanism to facilitate writing code and maintenance
1.static_cast 
2.dynamic_cast
3.const_cast
4.reinterpret_cast

four casts are called "cast named"
1.static_cast: static converters (can be understood as C-style casts, but the compiler will check its legality)
// common form 

// cast name <type> (express); 1.static_cast : static converters (can be understood as mandatory C-style revolution
to change, but the compiler will check its legality)
  can be use on
    . a related type of transformation (such as floating point type switch integer) 
    int I = static_cast <int> 100.0;
. B subclass conversion parent class (inheritance)
c.void conversion between the pointer and the other pointer * (to be cast the pointer type void *)
  Available for 
   a. Generally not used for conversion between different types of pointers
2.dynamic_cast: identifying a type of runtime checking mainly used. 
It is mainly used for converting between a parent type and subtype (the pointer to the parent subtype object type)

3.const_cast: removing pointers or references attribute const (compile-time type conversion) can not be converted between different types of
 
 
4. reinterpret_cast : reinterpreting (regardless of the type of conversion process) may milling, poor security 
  commonly used for both types of transformations as
a pointer to the integer conversion.
B the pointer type into another. type of pointer.
c. a pointer to an integer

IV Summary

1. The casts are not recommended, it will inhibit the compiler error

2. reinterpret_cast very dangerous, const_cast use means that a design flaw

3. If you really need to be cast, will have to use C ++ style casts

4. reinterpret_cast desirable to use as long as the rule, with the well

Guess you like

Origin www.cnblogs.com/sxgloverr1314/p/11517500.html