19_类型转换

类型转换

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

posted @   爱吃冰激凌的黄某某  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示