C++的显式类型转换
来源:互联网 发布:云计算的特征是什么 编辑:程序博客网 时间:2024/06/05 13:36
static_cast
For “well-behaved” and “reasonably well-behaved” casts, including things you
might now do without a cast (such as an automatic type conversion).
const_cast
To cast away const and/or volatile.
reinterpret_cast
To cast to a completely different meaning. The key is that you’ll need to
cast back to the original type to use it safely. The type you cast to is
typically used only for bit twiddling or some other mysterious purpose.
This is the most dangerous of all the casts.
dynamic_cast
For type-safe downcasting
C++除了支持C语言中的隐式类型转换,还提供了如上四种显式的类型转换。
1、reinterpret_cast
类型转换函数将一个类型的指针,转换为另一个类型的指针。这种转换不需要修改指针变量值数据存放格式,只需在编译时重新编译解释指针的类型就可。
double d=9.3;
double *pd=&d;
int *pi=reinterpret_cast<int*>(pd);
但是不能用于非指针类型的转换。
同隐式转换一样,reinterpret_cast也不能将一个const指针转换为void*指针。
2、const_cast
用于去除指针变量的常量属性,将它转换为一个对应指针类型的普通变量。也可以将一个非常量的指针变量转换为一个常指针变量,在编译期间做出类型更改。
const int* pci=0;
int* pj=const_cast<int*>(pci);
基于安全性的考虑,const_cast无法将非指针的常变量转换为普通变量。
可以将普通指针变量pi转换为常指针变量,但不能将非指针的普通变量转换为常变量。
3、static_cast
用于基本类型之间和具有继承关系的类型之间的转换,这种转换一般会更改变量的内部表示方式。用于指针类型转换,没有太大意义。
class Base();
class Derived:public Base{}
Derived d;
Base d=static_cast<Base>(d);
可将继承类对象转换为基类对象。但是反过来不行。
注意:基类指针转换为继承类指针,在一定的危害性。
4、dynamic_cast
与static_cast相对,是动态dynamic_cast转换。这种转换是在运行时进行转换分析的,并非在编译时进行。只能在继承类对象的指针之间或引用之间进行类型转换。进行转换时,会根据当前(RTTI)判断类型对象之间的转换是否合法。dynamic_cast转换失败,是通过是否为null指针检测;引用转换失败,抛出bad_cast异常。
将继承类指针或引用转换为基类指针或引用可以,反过来一般不行;但是如果基类中有虚函数也可以,也就是说被转换的类具有虚函数的对象指针时,编译也通过。
class Base();
class Derived:public Base{}
Derived *pd=new Derived;
Base *d=dynamic_cast<Base*>(pd);
此外,如果没有继承关系,但是被转换的类具有虚函数的对象指针时,转换也可编译通过。
int i;
long m;
m=static_cast<long>(i);
const int i=0;
int* j=(int*)&i;
j=const_cast<int*>(&i);//将const型转换成volatile.
************************************************************
#include "iostream"
using namespace std;
const int sz=100;
struct X
{
int a[sz];
};
void print(X* x)
{
for(int i=0;i<sz;i++)
cout<<x->a[i]<<' ';
cout<<endl<<"------------"<<endl;
}
int main()
{
X x;
print(&x);
int* xp=reinterpret_cast<int*>(&x);//cast &x to int*
for(int* i=xp;i<xp+sz;i++)
*i=0;
//cannot use xp as an X* at this point usless you cast it bakc;
print(reinterpret_cast<X*>(xp));
print(&x);
return 1;
}- C/C++的显式类型转换
- 逆天的C++:显式类型转换
- C的隐式类型转换
- C/C++的数值类型隐式类型转换
- c——显式类型转换
- C#.NET 的 类型转换
- C语言的类型转换
- C语言的类型转换
- C语言的类型转换
- c语言的类型转换
- C隐式类型转换
- C++/C指针的类型转换
- 关于C语言的隐式类型转换
- C/C++隐式类型转换导致的若干问题
- C语言隐式类型转换的规则
- 关于C语言的隐式类型转换
- <C/C++> 类型转换
- C/C++:类型转换
- 求二叉树的“胖”度
- C++:静态联编和动态联编
- POJ 1470 LCA
- c++中的显示转换
- java剪切图片
- C++的显式类型转换
- C++中的类型转换
- 从一道面试题谈linux下fork的运行机制
- Delphi 的接口机制——接口操作的编译器实现过程(1)
- Android中刻度尺实现
- ios获得通讯录中联系人的所有属性
- Linux之并发进程服务器
- 以BCD(16进制)码存储的Char数据以Int型表示
- Delphi 的接口机制——接口操作的编译器实现过程(2)