c++类型强制转换

1.const_cast

特性:1)可以去除变量的const 或者 volatile属性

void Type_transform::ConstCast()
{
    const Test t;
    t.s = "1111111"; //const 无法直接赋值 编译报错

    Test &tt  = const_cast<Test&>(t);
    tt.s = "1111111111"; //使用const_cast转换后取出了const属性可以正常赋值

}

2.static_cast

静态类型转换,基础类型的转换,不支持完全没有关系的两个类之间进行转换。

特性:1)由子类转成父类没有问题,但由父类转成子类不安全
2)完全没有关系的两个类之间不可以进行转换。

void Type_transform::StaticCast()
{
    Children *c = new Children;
    qInfo() << "c" << c->getParent() << endl;

    Parent *p = static_cast<Children*>(c); //子类转父类没有问题
    qInfo() << "p" << p->getParent() << endl;

    Parent *pp = new Parent;
    Children *cc = static_cast<Children*>(pp);

    if(cc != nullptr){
        qInfo() << cc->getParent() << endl;
        qInfo() << cc->getChildren() << endl; //父类转子类,调用子类成员函数时会出现问题
        //(当然会有问题,父类根本没有子类的函数~~)
    }

//    Test *t = new Test;
//    pp = static_cast<Parent *>(t); //完全不相关的类型不可以转换
    delete  c;
    delete  pp;
}

3.dynamic_cast

动态类型转换

特性:1)与static_cast相比,添加了由父类转为子类的检测,如果父类转换为子类会出错,返回一个空指针。
2)如果由父类转换为子类,父类一定要有虚函数,目的时可以生成虚函数表,让编译器知道父子类的关系,要不编译器会报错

void Type_transform::DynamicCast()
{

    Children *c = new Children;
    qInfo() << "c" << c->getParent() << endl;

    Parent *p = dynamic_cast<Children*>(c); //子类转父类没有问题
    qInfo() << "p" << p->getParent() << endl;

    Parent *pp = new Parent;
    Children *cc = dynamic_cast<Children*>(pp); //必须要有虚函数生成虚函数表,不然编译器报错
    if(cc != nullptr){ //转换出错,返回nullptr
        cc->getChildren();
    }

    delete  c;
    delete pp;
}

4.reinterpret_cast

仅重新解释类型,不知道有什么用(🙁)

void Type_transform::ReinterpretCast()
{
        Test *t = new Test;
        Parent *pp = reinterpret_cast<Parent*>(t); //编译不会报错 ,不知道这个类型强转有什么意义

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值