#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只能转换具有继承关系的指针或者引用
    //并且只能由子类转换成父类(范围只能由大到小,不能由小到大,否则会出现越界问题,不安全) 
     

//const_cat 指针  引用或者对象指针 
void test03(){
    
    //基础数据类型 
    int a = 10;
    const int& b = a;
    int& c = const_cast<int&>(b);  //变量c去除了const性 
    c = 20;
    cout<<"a = "<<a<<"  b = "<<b<<"  c = "<<c<<endl;
    
    //指针
    const int* p = NULL;
    int* p2 = const_cast<int*>(p); //变量 p2去除了const性 
    
    int* p3 = NULL;
    const int* p4 = const_cast<const int*>(p3); //变量p4增加了const性 
    
    //const_cat  增加或者去除变量的const性 
}

//  reinterpret_cast  强制类型转换
typedef void(*FUNC1) (int, int);
typedef void(*FUNC2) (int, char*);
void test04(){
    
    // 无关的指针类型都可以进行转换 
    Building*  building= NULL;
    Animal* ani = reinterpret_cast<Animal*>(building);
     
    //  函数指针转换 
    FUNC1 func1;
    FUNC2 func2 = reinterpret_cast<FUNC2>(func1);

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

【C++】10 类型转换const_cast和reinterpret_cat

相关文章:

  • 2021-07-12
  • 2022-12-23
  • 2021-06-11
猜你喜欢
  • 2021-12-05
  • 2022-12-23
  • 2021-05-06
  • 2021-06-29
  • 2021-12-04
  • 2022-01-23
  • 2021-12-05
相关资源
相似解决方案