c++的类型转换


用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换
进行上行转换:用 父类指针、引用 指向 子类空间(安全)
进行下行转换:用 子类指针、引用 指向 父类空间(不安全)

在这里插入图片描述

1、静态类型转换(static_cast)

可作用于 基本类型

可用于 自定义数据类型(结构体 类)

不能作用于 不相关的类之间转换

class Animal{};
class Dog:public Animal{};
class Other{};


//静态转换static_cast
void test01()
{
    //static_cat 作用于 基本类型
    char ch = 'a';
    double d = static_cast<double>(ch);
    cout<<"d = "<<d<<endl;

    //static_cat 作用于 自定义数据类型(结构体 类)
    //关系的类之间
    //上行转换 安全
    Animal *p1 = static_cast<Animal *>(new Dog);
    //下行转换  不全 容易越界
    Dog *p2 = static_cast<Dog *>(new Animal);

    // static_cast 不能作用域 不相关的类之间转换
    //Animal *p3 = static_cast<Animal *>(new Other);//err
}

2、动态转换dynamic_cast 2-1

不支持 基本类型

可以上行转换 (父类指针 指向 子类空间 安全)

不支持下行转换 (子类指针 指向 父类空间 不安全)

不支持 没有关系的 类型转换

//dynamic_cast动态转换
void test02()
{
    //1、dynamic_cast不支持 基本类型
    char ch = 'a';
    //double d=dynamic_cast<double>(ch);//err

    //2、dynamic_cast 上行转换 (父类指针 指向 子类空间 安全)
    Animal *p1  = dynamic_cast<Animal *>(new Dog);

    //3、dynamic_cast 下行转换 (子类指针 指向 父类空间 不安全)
    //Dog *p2 = dynamic_cast<Dog *>(new Animal);//不支持 不安全 的转换

    //4、dynamic_cast 不支持 没有关系的 类型转换
    //Animal *p3 = dynamic_cast<Animal *>(new Other);//err
}

3、常量转换const_cast

支持常量指针转为不同指针

不支持 非指针或引用的转换

支持常量引用 转换成 普通引用

//常量转换const_cast
void test03()
{
    const int *p = NULL;
    int *p1 = const_cast<int *>(p) ;

    int *p2 = NULL;
    const int *p3 = const_cast<const int *>(p2);

    //const_cast 不支持 非指针或引用的转换
    const int a = 100;
    //int b = const_cast<int>(a);//err

    int data = 100;
    //常量引用 转换成 普通引用
    const int &ob = data;
    int &ob2 = const_cast<int &>(ob);
}

4、重新解释转换(reinterpret_cast)

不支持基本数据类型

支持不相关的类型间转换

支持上行下行转换

void test04()
{

    //reinterpret_cast 不支持基本数据类型
    char ch='a';
    //double d = reinterpret_cast<double>(ch);//err

    //reinterpret_cast 支持 不相关的类型间转换
    Animal *p1 = reinterpret_cast<Animal *>(new Other);

    //上行转换
    Animal *p2 = reinterpret_cast<Animal *>(new Dog);

    //下行转换
    Dog *p3 = reinterpret_cast<Dog *>(new Animal);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值