【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;
}

 

 

 

 

 

 

 

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