在 C++语言中新增了四个关键字 static_cast、const_cast、reinterpret_cast 和 dynamic_cast。这四个关键字都是用于强制类型转换的
static_cast
static_cast 用于数据类型的强制转换,强制将一种数据类型转换为另一种数据类型。例如将浮点型数据转换为整型数据
//static_cast
double d = 3.1415;
int i = static_cast<int>(d); //打印3
cout << "static_cast:" << i << endl;
const_cast
在 C语言中,const 限定符通常被用来限定变量,用于表示该变量的值不能被修改。而 const_cast 则正是用于强制去掉这种不能被修改的常数特性,但需要特别注意的是,const_cast 不是用于去除变量的常量性,而是去除指向常数对象的指针或引用的常量性,其去除常量性的对象必须为指针或引用。
const int* Search(const int* a, int n, int val)
{
int i;
for (i = 0; i < n; i++)
{
if (a[i] == val)
return &a[i];
}
return NULL;
}
void test_const_cast()
{
const int a = 10; //定义a是常量,其值不能被修改
const int* p = &a;
//*p = 20; //修改a的值,compile error
//int b = const_cast<int>(a); //compile error,const_cast 强制转换对象必须为指针或引用
int* q;
q = const_cast<int*>(p);
*q = 20; //fine
cout << a << " " << *p << " " << *q << endl; //10 20 20
//a 是常量不允许修改,但又修改成功,在c++中叫为未定义行为语句
//未定义行为是指在标准的 C++ 规范中并没有明确规定这种语句的具体行为,该语句的具体行为由编译器来自行决定如何处理
cout << &a << " " << p << " " << q << endl; //0098F7E4 0098F7E4 0098F7E4
//p q 也都指向a,
int arr[10] = { 0,1,2,3,4,5,6,7,8,9 };
int val = 5;
int* p1;
p1 = const_cast<int*>(Search(arr, 10, val)); //强制去掉常量特性,是合法的,const_cast的体现之处,但不建议用
if (p1 == NULL)
cout << "Not found the val in array a" << endl;
else
cout << "have found the val in array a and the val = " << *p1 << endl; //走else
}
reinterpret_cast
在 C++语言中,reinterpret_cast 主要有三种强制转换用途:
- 改变指针或引用的类型
- 将指针或引用转换为一个足够长度的整形
- 将整型转换为指针或引用类型。
在使用 reinterpret_cast 强制转换过程仅仅只是比特位的拷贝,这种转换是非常底层和危险的,因为它不进行任何验证或保证转换后的类型是否有效或安全
int a = 42;
int* pInt = &a; // 整数指针
char* pChar = reinterpret_cast<char*>(pInt); // 将整数指针转换为字符指针
cout << "Integer value: " << *pInt << endl; //42
cout << "Char value (reinterpreted): " << static_cast<int>(*pChar) << endl; // 输出该位置的字符的整数值(通常是ASCII码)