1 首先来回顾 C 的强制转换
大家都知道, 在编译 C 语言中的强制转换时, 编译器不会检查转换是否成功, 都会编译正确.
比如:
- #include "stdio.h"
- struct Position
- {
- int x;
- int y;
- };
- int main()
- {
- int i;
- struct Position *p;
- i=0x123456;
- p=(struct Position *)i;
- printf("px=%d,py=%d\n",p->x,p->y);
- }
输出结果如下图所示:
从上图可以看到, 只有当运行代码时, 才会出现段错误问题.
当 C 代码上千行时, 若出现这种问题, 是非常难找的.
2.C++ 的新型类型转换
所以在 C++ 中, 便引入了 4 种强制类型转换
2.1 static_cast(静态类型转换)
用于基本数据类型之间的转换 (char,int,const int 等)
不能用于基本数据类型指针之间的转换 (char *,int * 等)
用于有继承关系类对象之间的转换
用于类指针之间的转换
例如:
- int i = 0x45;
- char c = 'c';
- c = static_cast<char>(i);
- //char* pc = static_cast<char*>(&i); // 此行错误, 不能用于基本指针之间转换
2.2 const_cast(去常类型转换)
用于去除变量的只读属性
且强制转换的类型必须是指针 * 或引用 &
例如:
- const int x =1; //const: 定义一个常量 x
- const int& j =2; //const 引用: 定义一个只读变量 j
- int& p1= const_cast<int&>(x); // 强制转换 int &
- int *p2 = const_cast<int*>(&j); // 强制转换 int*
- //int p3 = const_cast<int>(j); // 此行错误, 不能转换普通数据型
- p1=3;
- *p2=4;
- printf("x=%d, j=%d\n",x,j);
- printf("p1=%d *p2=%d\n",p1,*p2);
输出结果:
- x=1 j=4
- p1=3 *p2=4
从输出结果, 可以看出修改 p1,p2, 只有 j 内容变换了, 是因为变量 j 用 const 引用定义的, 所以是个只读变量.
2.3 dynamic_cast(动态类型转换)
用于有继承关系的类指针间的转换
用于有交叉关系的类指针间的转换
具有类型检查的功能
需要虚函数的支持
不能用于基本数据类型指针之间的转换 (char *,int * 等)
2.4 reinterpret_ cast(解读类型转换)
用于所有指针的强制转换
(解读是指: 对要转换的数据进行重新的解读)
例如:
- int i = 0;
- char j='c';
- int *p1=reinterpret_cast<int *>(&i);
- char *p2=reinterpret_cast<char *>(&j);
- //int p3=reinterpret_cast<int >i; // 此行错误, 不能转换普通数据型
来源: https://www.cnblogs.com/lifexy/p/8456000.html