C++中的static_cast的用法

参考博客:1、https://blog.csdn.net/moruihong/article/details/7712260?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control

2、https://blog.csdn.net/zhouwei1221q/article/details/44978361

3、https://blog.csdn.net/u014624623/article/details/79837849?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control

一、主要应用于以下情形:

1、用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换。
进行上行转换(把派生类的指针或引用转换成基类表示)是安全的;
进行下行转换(把基类指针或引用转换成派生类表示)时,由于没有动态类型检查,所以是不安全的。
2、用于基本数据类型之间的转换,如把int转换成char,把int转换成enum。
3、把空指针转换成目标类型的空指针。
4、把任何类型的表达式转换成void类型。

二、转换

1、类转换:

Class Partent{};
Class Child : public Partent {};

Child *a = new Child();
Partent *b = static_cast<Partent *>(a);(上行转换是安全的)


Partent *b = new Partent();
Child *a = static_cast<Child*>(b);(下行转换是不安全的,不能使用)

2、基本类型的转换

int a = 10;

float b = static_cast<float>(a);

3、void *类型的转换

int a = 10;
void *p = &a;
int *i = static_cast<int *>(p);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值