c和c++的强制类型转换

我们知道c语言中的类型转换只有一种,

TYPE b = (TYPE)a;

而在c++中按照不同作用的转换类型将其细分为三个显示类型转换符号static_cast, const_cast, reinterpret_cast,这种显示转换可以提供更丰富的含义和功能,更好的类型检查机制,方便代码的维护。

1.static_cast

  • 主要用于相关类型之间的转换,如c的基本数据类型char,int,double等之间,以及基类和子类之间转换(没有dynamic_cast安全),可能会有字节转换,不可以转换不相关类型如int*和double*,以及没有继承关系的类指针
  • void*与其他类型指针之间的转换
double bv = 100.0
int i = (int)bv;  //c style, 0x64
int iv2 = static_cast<int>(bv); //0x64
int iv2 = reinterpret_cast<int>(bv); //error,

double bv = 100.0;
double *pbv = &bv;
int *iv1 = (int*)pbv; //c style, right
int *iv2 = static_cast<int*>(pbv); //error: invalid static_cast from type `double*' to type `int*'
int *iv2 = reinterpret_cast<int*>(pbv); //right, 
void *piv1 = (void*)pbv;
void *piv2 = static_cast<void*>(pbv);
int *piv3 = static_cast<int*>(piv2); //right

2.reinterpret_cast

  • 转换的类型type必须是一个指针或引用,仅仅按照转换后的类型重新解释字节,并不会做字节转换
  • 如果将非指针变量转换成指针,变量大小必须与指针大小相等。
  • 移植性差
int lv = 100;
long long llv =100;
int *piv1 = (int*)lv;  //c style, do’not check size
int *piv2 = reinterpret_cast<int*>(lv); //lv is treated as pointer
piv2 = reinterpret_cast<int*>(llv); // warning, different size

3.const_cast

去除指针或者引用的const或volatile属性

//c style
const char const_char = 'a';
char *pch = &const_char;  //error: invalid conversion from `const char*' to `char*'
char *pch = (char*)&const_char; //right
*pch = 'c'; 

//c++style
const char const_char = 'a';
char chv = const_cast<char>(const_char); //error, invalid use of const_cast with type `char', which is not a pointer, reference, nor a pointer-to-data-member type
const char *pch = &const_char;
char *chv = const_cast<char*>(&const_char);//right
*chv=’c’;

总结:这三种与c对应的强制类型转换符号都是编译时确定的,RTTI的dynamic_cast和c没有关系,以后再专门介绍。


作者:coderkian
出处:http://www.cnblogs.com/coderkian/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/coderkian/p/3484641.html