C编译器无法保证强制类型转换的正确性。
C++强制类型转换分4种类型:
强制类型转换
static_cast | const_cast |
dynamic_cast | reinterpret_cast |
static_cast
- 用于基本类型间的转换
- 不能用于基本类型指针间的转换
- 可用于有继承关系类对象间的转换和类指针间的转换
const_cast
- 用于去除变量的只读属性
- 强制类型转换的目标类型必须是指针或引用
reinterpret_cast
- 用于指针类型间的强制转换
- 用于整数和指针类型间的强制转换
dynamic_cast
- 用于有继承关系的类指针间的转换
- 用于有交叉关系的类指针间的转换
- 具有类型检查的功能
- 需要虚函数支持
#include <stdio.h>
void static_cast_demo()
{
int i = 0x12345;
char c = 'c';
int* pi = &i;
char* pc = &c;
c = static_cast<char>(i); //static_cast可用于基本类型间的转换
// pc = static_cast<char*>(pi); //error,static_cast不能用于基本类型指针间的转换
}
void const_cast_demo()
{
const int& j = 1; //只读变量
int& k = const_cast<int&>(j); //const_cast可用于去除变量的只读属性
const int x = 2; //常量
int& y = const_cast<int&>(x); //编译器还是会为常量x在内存空间中分配内存,y就是这片内存的别名
// int z = const_cast<int>(x); //error,const_cast目标类型必须是指针或引用
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); //reinterpret_cast可用于指针类型间的强制转换
pi = reinterpret_cast<int*>(pc);
pi = reinterpret_cast<int*>(i); //reinterpret_cast可用于整数和指针类型间的强制转换
// c = reinterpret_cast<char>(i); //error,reinterpret_cast不能用于基本类型间的转换
}
/*dynamic_cast_demo:
* -用于有继承关系的类指针间的转换
* -用于有交叉关系的类指针间的转换
* -具有类型检查的功能
* -需要虚函数支持
*/
void dynamic_cast_demo()
{
int i = 0;
int* pi = &i;
// char* pc = dynamic_cast<char*>(pi); //error
}
int main()
{
static_cast_demo();
const_cast_demo();
reinterpret_cast_demo();
dynamic_cast_demo();
return 0;
}