19_类型转换

发布时间 2023-10-15 14:50:04作者: 爱吃冰激凌的黄某某

类型转换

static_cast 静态类型转换

class Base{};
class Son: public Base{};
class Other{};

1用于父类和子类之间指针或引用的转换

基本类型: 支持

int num = static_cast<int>(3.14); //ok

2上行转换: 支持 安全

Base *p = static_cast<Base *>(new Son);

3下行转换: 支持(不安全)

Son *p2 = static_cast<Son *>(new Base);

4不相关类型转换: 不支持

Base *p3 = static_cast<Base *>(new Other); //error

dynamic_cast 静态类型转换

1dynamic_cast主要用于类层次间的上行转换和下行转换

基本类型: 不支持

int num = dynamic_cast<int>(3.14); //error

2上行转换: 支持

Base *p1 = dynamic_cast<Base *>(new Son); //ok

3下行转换: 不支持(不安全)

Son *p2 = dynamic_cast<Son *>(new Son); //error

4不相关类型转换: 不支持

Base *p3 = dynamic_cast<Base *>(new Other); //error

const_cast 常量转换

1将const修饰的指针或引用转换成 非const(支持)

const int *p1;
int *p2 = const_cast<int *>(p1);

const int &ob = 10;
int &ob1 = const_cast<int &>(ob);

2将非const修饰的指针或引用转换成 const(支持)

int *p3;
const int *p4 = const_cast<const int *>(p3);

int data = 10;
const int &ob2 = const_cast<const int &>(data);

重新解释转换(reinterpret_cast) (最不安全)

image-20231011172716182