C++中的四种类型转换

//1.常见的类型转换,使用static_cast
float f = 1.234;
int i =static_cast<int>(f);//等价于 int i = (int)f;

//2.const_cast,将常量指针(指针指向的地址的值不能变)转变成非常量指针
int a = 1;
const int * b = &a;
*(const_cast<int*>(b)) = 2;

//3.dynamic_cast,主要用于子类父类之间的转换,使用这个关键字进行转换会在转换时进行类型检查,检测类型是否合法。
//用于多态,也就是说要转换的类必须有虚函数。

//4.reinterpret_cast是解释的意思,reinterpret即为重新解释,
//此标识符的意思即为数据的二进制形式重新解释,但是不改变其值。如:
int j;
char *ptr = "a";
j =reinterpret_cast<int >(ptr);//这个转换方式很少使用。
return 0;

原文地址:https://www.cnblogs.com/merlinzjl/p/8011829.html