C++之类型转化

类型转换

1、上行、下行转换

在这里插入图片描述

2、static_cast静态类型转换

用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换

class Person{};

class Son:public Person{};

class Other{};
//基本类型转换
int num=static_cast<int>(3.14);//支持
//上行转换
Person *p=static_cast<Person *>(new Son);//支持
//下行转换 (不安全)
Son *p2=static_cast<Son *>(new Person);//支持
//不相关类型转换
Person *p3=static_cast<Person *>(new Other);//不支持

3、dynamic_cast动态类型转换

dynamiccast主要用于类层次间的上行转换

//基本类型转换
int num=dynamic_cast<int>(3.14);//不支持
//上行转换
Person *p=dynamic_cast<Person *>(new Son);//支持
//下行转换
Son *p2=dynamic_cast<Son *>(new Person);//不支持
//不相关类型转换
Person *p3=dynamic_cast<Person *>(new Other);//不支持


4、const_cast常量转换

1、将const修饰的指针或引用转换成非const (支持)

    const int *p1;
    int *p=const_cast<int *>(p1);
    
    const int &a=10;
    int &b=const_cast<int &>(a);

2、将非const修饰的指针或引用 转换成 const (支持)

    int *p3;
    const int *p4=const_cast<const int *>(p3);


    int data=10;
    const int &ob2=const_cast<const int &>(data);

5、重新解释转换(reinterpret_cast) (最不安全)

    //基本类型
    int num=reinterpret_cast<int>(3.14);//不支持
    
    //基本类型指针:
    float *q;
    int *p=reinterpret_cast<int *>(q);//支持

    //上行转换
    Person *person=reinterpret_cast<Person *>(new Son);//支持

    //下行转换
    Son *son=reinterpret_cast<Son *>(new Person);//支持

    //不相关类型转换
    Person *person2=reinterpret_cast<Person *>(new Other);//不支持
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值