C++的显式类型转换

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语言中的隐式类型转换,还提供了如上四种显式的类型转换。

1reinterpret_cast

    类型转换函数将一个类型的指针,转换为另一个类型的指针。这种转换不需要修改指针变量值数据存放格式,只需在编译时重新编译解释指针的类型就可。

double d=9.3;

double *pd=&d;

int *pi=reinterpret_cast<int*>(pd);

但是不能用于非指针类型的转换。

同隐式转换一样,reinterpret_cast也不能将一个const指针转换为void*指针。

2const_cast

    用于去除指针变量的常量属性,将它转换为一个对应指针类型的普通变量。也可以将一个非常量的指针变量转换为一个常指针变量,在编译期间做出类型更改。

const int* pci=0;

int* pj=const_cast<int*>(pci);

基于安全性的考虑,const_cast无法将非指针的常变量转换为普通变量。

    可以将普通指针变量pi转换为常指针变量,但不能将非指针的普通变量转换为常变量。

3static_cast

    用于基本类型之间和具有继承关系的类型之间的转换,这种转换一般会更改变量的内部表示方式。用于指针类型转换,没有太大意义。

class Base();

class Derived:public Base{}

Derived d;

Base d=static_cast<Base>(d);

可将继承类对象转换为基类对象。但是反过来不行。

注意:基类指针转换为继承类指针,在一定的危害性。

4dynamic_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;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值