分析如下代码:
#include <stdio.h>
typedef void(PF)(int);
struct Point
{
int x;
int y;
};
int main()
{
int v = 0x12345;
PF* pf = (PF*)v;
char c = char(v);
Point* p = (Point*)v;
pf(5);
printf("p->x = %d\n", p->x);
printf("p->y = %d\n", p->y);
return 0;
}
分析:
该代码是C语言中强制类型的的Demo, 将它在Linux环境下编译,没有任何错误,一运行就发生段错误。
由此可得C语言强制装换存在如下问题:
而我们在实际开发中强制类型转换在实际工程中是很难完全避免的,因此需要更安全可靠的转换。
C++提出了新的类型转换:
使用方法:
xxx_cast<type>(expression);
Static_cast 强制类型转换
- 用于基本类型间的转换
- 不能用于基本类型指针间的转换
- 用于有继承关系类对象之间的转换和类指针的之间的转换
Const_cast 强制类型转换
- 用于去除变量的只读属性
- 强制类型转换的目标类型必须是指针或引用
Reinterpret_cast强制类型转换
- 用于指针类型间的强制转换
- 用于整数和指针类型间的强制转换(嵌入式里面开发用到)
Dynamic_cast强制类型转换
- 用于有继承关系的类指针间的转换
- 用于有交叉关系的类指针间的转换
- 具有类型检查功能
- 需要虚函数的支持
void static_cast_demo()
{
int i = 0x12345;
char c = 'c';
int* pi = &i;
char* pc = &c;
c = static_cast<char>(i);
pc = static_cast<char*>(pi); // error
}
void const_cast_demo()
{
const int& j = 1;
int& k = const_cast<int&>(j);
const int x = 2;
int& y = const_cast<int&>(x);
int z = const_cast<int>(x); // error 必须是指针或者引用
k = 5;
printf("k = %d\n", k);
printf("j = %d\n", j);
y = 8;
printf("x = %d\n", x);
printf("y = %d\n", y);
printf("&x = %p\n", &x);
printf("&y = %p\n", &y);
}
void reinterpret_cast_demo()
{
int i = 0;
char c = 'c';
int* pi = &i;
char* pc = &c;
pc = reinterpret_cast<char*>(pi);
pi = reinterpret_cast<int*>(pc);
pi = reinterpret_cast<int*>(i);
c = reinterpret_cast<char>(i); // error 不能用于普通类型转换
}
void dynamic_cast_demo()
{
int i = 0;
int* pi = &i;
char* pc = dynamic_cast<char*>(pi); // error 必须要虚函数的存在
}
小结
1.新式类型转换编译器能够帮我们检查潜在的问题
2.非常方便在代码中定位
3.支持动态类型识别(dynamic_cast)