类型转换
1、上行、下行转换
2、static_cast静态类型转换
用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换
class Person{};
class Son:public Person{};
class Other{};
//基本类型转换
int num=static_cast<int>(3.14);//支持
//上行转换
Person *p=static_cast<Person *>(new Son);//支持
//下行转换 (不安全)
Son *p2=static_cast<Son *>(new Person);//支持
//不相关类型转换
Person *p3=static_cast<Person *>(new Other);//不支持
3、dynamic_cast动态类型转换
dynamiccast主要用于类层次间的上行转换
//基本类型转换
int num=dynamic_cast<int>(3.14);//不支持
//上行转换
Person *p=dynamic_cast<Person *>(new Son);//支持
//下行转换
Son *p2=dynamic_cast<Son *>(new Person);//不支持
//不相关类型转换
Person *p3=dynamic_cast<Person *>(new Other);//不支持
4、const_cast常量转换
1、将const修饰的指针或引用转换成非const (支持)
const int *p1;
int *p=const_cast<int *>(p1);
const int &a=10;
int &b=const_cast<int &>(a);
2、将非const修饰的指针或引用 转换成 const (支持)
int *p3;
const int *p4=const_cast<const int *>(p3);
int data=10;
const int &ob2=const_cast<const int &>(data);
5、重新解释转换(reinterpret_cast) (最不安全)
//基本类型
int num=reinterpret_cast<int>(3.14);//不支持
//基本类型指针:
float *q;
int *p=reinterpret_cast<int *>(q);//支持
//上行转换
Person *person=reinterpret_cast<Person *>(new Son);//支持
//下行转换
Son *son=reinterpret_cast<Son *>(new Person);//支持
//不相关类型转换
Person *person2=reinterpret_cast<Person *>(new Other);//不支持