#include<iostream>usingnamespace std;classBuilding{};classAnimal{};classCat:public Animal {};//测试static_cast的用法voidtext1(){//转换基础数据类型int a =97;char b =static_cast<char>(a);
cout <<"text1: b = "<< b << endl;//转换为对应的ASCII码值//只能转换具有继承关系的指针,即不能转为Building类型
Animal* animal =NULL;
Cat* cat1 =static_cast<Cat*>(animal);//具有继承关系的引用之间进行转换
Animal ani;
Animal& aniref = ani;
Cat& catref =static_cast<Cat&>(aniref);}/*
dynamic_cast动态类型转换
只能转换具有继承关系的指针或引用,但在转换前会进行对象数据类型的检查
子类指针可以转换为父类指针(包含内容从大变小)
由于父类指针转换成子类指针可能会涉及父类所不具有的属性与方法
并不安全,所以dynamic_cast在进行安全检查时会拒绝这种转换
*/voidtext2(){
Cat* cat1 =NULL;
Animal* ani =dynamic_cast<Animal*>(cat1);}//测试const_cast的用法//针对指针,引用或者对象指针//主要用来增加或者去除变量的const属性voidtext3(){//引用部分int a =10;constint& b = a;//b由const修饰不能进行修改int&c=const_cast<int&>(b);//经过类型转换c是整型引用,可以进行修改
cout <<"text3:c修改前:a= "<< a <<" b = "<< b <<" c = "<< c << endl;
c =25;
cout <<"text3:c修改前:a= "<< a <<" b = "<< b <<" c = "<< c << endl;//指针部分constint* p =NULL;int*p2=const_cast<int*>(p);int* p2 =NULL;}//测试reinterpret_cast的用法//强制类型转换,用于进行没有任何关联之间的转换voidtext4(){//无关的指针都可以进行转换
Building* build =NULL;
Animal* ani =reinterpret_cast<Animal*>(build);}intmain(){text1();text3();return0;}