C++深入理解(11)------关于static_cast,dynamic_cast,const_cast,reinterpret_cast(读书笔记)

        C语言规定了很多的隐式转化,如将int转为double等,但是隐式转化时长会造成一些问题,所以在C++中定义了四种规范转换方式,来规范转化。下面依次讲述下每个转化的用法:

        dynamic_cast:智能用于将派生类指针转化为基类指针,否则就会赋空值。这种转化只能用于is-a类型的转化,用法如下:

    BaseClass *pBase = dynamic_cast<BaseClass*>(pSub);
        const_cast:只用于一种用途,即将const转化为volatile,其语法
High bar ;
const High *pbar = &bar ;
High *pb = const_cast<High*> (pbar); //正确的,将pbar转化为可以非const
const Low *pi = const_cast<const Low *> (pbar); //非法的,如果将pbar转化为非const,但是又转化为const
        其他转换都是非法的;

        static_cast:只能转化可以隐式转化的类型,如double可以隐式转化为int,派生类指针可以隐式转化为基类指针,但是基类指针转化为派生类指针就会报错;

        reinterpret_cast:功能比较强大,他可以根据内存中的值转化为另一种类型,如

struct dat {short a ; short b ;};
long value = 0xA224B118;
dat * pd = reinterpret_cast<dat*> (&value );
cout << hex << pd->a ; / / display first 2 bytes of value
        dat的内存是连续的,将long在内存中的位置的指针位置给dat,同时将long转化为dat类型。有时处理结构体异常有用。

猜你喜欢

转载自blog.csdn.net/xiaopengshen/article/details/79732949