【C++】09 类型转换static_cast和dynamic_cat

#include<iostream>
using namespace std;

class Building{};
class Animal{};
class Cat : public Animal{};

void test(){
    int a = 98;
    char c = static_cast<char>(a); 
    cout<<c<<endl;  //输出ASCLL值为98的字符 
    
    //基础数据类型指针 
    //int*p = NULL;
    //char* sp = static_cast<char*>(p);  无法转换 
    
    //对象指针 
    //Building* building = NULL;
    //Animal* ani = static_cast<Building*>(building);  无法转换 
    
    //转换具有继承关系的对象指针
    Animal* ani = NULL;
    Cat* cat = static_cast<Cat*>(ani);
    
    //子类指针转换成父类指针 
    Cat* soncat = NULL;
    Animal* anifather = static_cast<Animal*>(soncat);
    
    //引用 
    Animal aniobj;
    Animal& aniref = aniobj; 
    Cat& cat01 = static_cast<Cat&>(aniref); 
    
    Cat catobj;
    Cat& catref = catobj;
    Animal& anifather2 = static_cast<Animal&>(catref);
    
    //static_cat 用于内置的数据类型
    //还有具有类型关系的指针或者引用 

    //dynamic_cast  转换具有继承关系的指针或者引用,在转换前会进行队形类型检查 
void test02(){
    //基础数据类型 
    //int a = 10;
    //char c = dynamic_cast<char>(a);     转换失败
    
    //非继承关系的指针
    //Animal* ani = NULL;
    //Building* building = dynamic_cast<Building*>(ani);  转换失败  
    
    //具有继承关系指针
    //Animal* ani = NULL;
    //Cat* cat = dynamic_cast<Cat*>(ani);   转换失败
    //原因在于dynamic_cast 会做安全检查 
    
    Cat *cat = NULL;
    Animal* ani = dynamic_cast<Animal*>(cat);
    
    //结论: dynamic_cast只能转换具有继承关系的指针或者引用
    //并且只能由子类转换成父类(范围只能由大到小,不能由小到大,否则会出现越界问题,不安全) 
     

int main(){
    test();
    return 0;
}

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值