C++中的类型转换

C++支持四种类型转换:

static_cast, dynamic_cast, const_cast, reinterpret_cast

 

具体用法如下:

  1. const_cast用来添加/删除变量的const/volatile属性
  2. static_cast用于数值类型之间的转换,以及指针相关类型之间的转换
  3. dynamic_cast用于在运行期转换指针和引用,一般用于在继承层次中对指针和引用向上/下转型
  4. reinterpret_cast用于所有不具有移植性的转换,应尽量避免使用这种转换。
  1. The const_cast is used to add/remove const(ness) (or volatile-ness) of a variable.
  2. The static_cast is used to cast between numeric types. Static cast is also used to cast pointers to related types. For example, it can cast void* to the appropriate pointer type or vice-versa.
  3. The dynamic_cast is used to convert pointers and references at run-time, generally for the purpose of casting a pointer or reference up or down an inheritance chain (inheritance hierarchy).
  4. The reinterpret_cast is used for all non portable casting operations. This makes it simpler to find these non portable casts

when porting an application from one OS to another.

你可能感兴趣的:(C++中的类型转换)