例说 const_cast,reinterpret_cast,static_cast,dynamic_cast

 // TypeChange.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

class A
{

};

class B
{

};

class AA : public A
{

};

class BB : public B
{

};


int main(int argc, char* argv[])
{
        A* a = new A;
        B* b = new B;
        AA* aa = new AA;
        BB* bb = new BB;

        A* pA = 0;
        B* pB = 0;
        AA* pAA = 0;
        BB* pBB = 0;
        void* pVoid = 0;


        //const_cast,reinterpret_cast,static_cast,dynamic_cast
        // static_cast 对于在同一继承链上的类型转换
        pAA = static_cast<AA*>(a);     // down-casting   不安全 
        pA = static_cast<A*>(aa);     // up-casting     安全
        // pBB = static_cast<BB*>(aa);    // 编译错误, 不在同一条继承链上
        // pBB = static_cast<A*>(aa);    // 编译错误, 不在同一条继承链上
        pVoid = static_cast<A*>(aa);    // 但这样做可以
        pA = static_cast<AA*>(aa);     // 这个可以(就是pA = aa;了) 
        //pAA = static_cast<A*>(a);     // 编译错误(就是pAA = a;了)

        // dynamic_cast 对于在同一继承链上的类型转换, 
        // 不允许从父类类型换到子类类型, 但static_cast可以
        //pAA = dynamic_cast<AA*>(a);    // 编译错误, 不能从父类类型转A*换到子类类型AA*
        pA = dynamic_cast<A*>(aa);     // 子类类型AA*转换到父类类型A* 安全
        // pBB = dynamic_cast<BB*>(aa);    // 编译错误, 不在同一条继承链上
        //pBB = dynamic_cast<A*>(aa);    // 编译错误, 不在同一条继承链上
        pVoid = dynamic_cast<A*>(aa);    // 但这样做可以

        // reinterpret_cast 任意类型的转换, 不安全
        // pBB = reinterpret_cast<A*>(aa);   // 编译错误, 尖括号中的A* 与pBB的类型不一致
        pBB = reinterpret_cast<BB*>(aa);   // 任意类型的转换, 不安全


        // const_cast 就是用户去除变量的const属性了
        // 上面上个转换符对于const变量到非const变量的转换是编译不过的
        const A* ca = new A;
        const B* cb = new B;
        const AA* caa = new AA;
        const BB* cbb = new BB; 
        A* pCA = 0;
        B* pCB = 0;
        AA* pCAA = 0;
        BB* pCBB = 0;

        pCA = const_cast<A*>(ca);   // 相同类型的const变量转换为非const变量
        //pCA = const_cast<A*>(cb);   // 编译错误, 类型不同
        //pCA = const_cast<A*>(caa);  // 编译错误, 类型不同, 同一条继承链上的也不行


        delete a;
        delete b;
        delete aa;
        delete bb;
        delete const_cast<A*>(ca);   // delete也需要转换
        delete const_cast<B*>(cb);
        delete const_cast<AA*>(caa);
        delete const_cast<BB*>(cbb);

        return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值