C++新式转型之dynamic_cast

本文详细探讨了C++中的dynamic_cast关键字,主要用于安全的向下转型。内容包括downcast和sidecast的解释,以及转型失败的情况。dynamic_cast不仅用于检查继承关系,还能在运行时检查对象实际类型,确保安全的转型操作。
摘要由CSDN通过智能技术生成

dynamic_cast的文章看了很多,大多是说,“可以这样做,不可以这样做”,今天花了半天时间,仔细学了一下,收获颇丰。整理了一下,比较乱,很多东西依然模棱两可,有机会看了《深入理解C++对象模型》之后再好好补充。

dynamic_cast

主要用来执行“安全向下转型”,也就是用来决定某对象是否归属继承体系中的某个类型。

dynamic_cast是用来检查两者是否有继承关系。因此该运算符实际上只接受基于类对象的指针和引用的类转换。

来看cppreference上面的说法:

dynamic_cast < new_type > ( expression )        

1) If the type of expression is exactly new_type or a less cv-qualified version of new_type, the result is the value of expression, with type new_type. (In other words, dynamic_cast can be used to add constness. An implicit cast and static_cast can perform this conversion as well.)

class Fuck
{
public:
    int a;
    Fuck():a(10){}
    ~Fuck(){}
};

int main() {
    Fuck f;
    const Fuck *pb = dynamic_cast< const Fuck *>(&f);
    //const Fuck b = dynamic_cast< const Fuck >(f);//error:必须是指向完整类类型指针或者void*
    const Fuck cf;
    //Fuck *pc=dynamic_cast<Fuck*>(&cf);//error:这件事应该交给const_cast
    cout << pb->a << endl;//输出10
    system("pause");
    }

类型一致没什么好说的,这跟static_cast行为一致。并且可以对less-cv的type做const转型,用原文的话来说:dynamic_cast can be used to add constness

2) If the value of expression is the null pointer value, the result is the null pointer value of type new_type.

空指针的转型将得到新类型的空指针。

3) If new_type is a pointer or reference to Base, and the type of expression is a pointer

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值