通过shared_ptr进行dynamic_cast吗? [英] dynamic_cast across a shared_ptr?

查看:381
本文介绍了通过shared_ptr进行dynamic_cast吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类A和B,B继承自A.

I have two classes A and B, B inherits from A.

如果我有一个确实是B子类型的shared_ptr<A>对象,我该如何执行动态强制转换以访问B的API(请记住我的对象是shared_ptr,而不仅仅是A?

If I have a shared_ptr<A> object which I know is really a B subtype, how can I perform a dynamic cast to access the API of B (bearing in mind my object is shared_ptr, not just A?

推荐答案

如果只想从B调用函数,则可以使用以下之一:

If you just want to call a function from B you can use one of these:

std::shared_ptr<A> ap = ...;
dynamic_cast<B&>(*ap).b_function();
if (B* bp = dynamic_cast<B*>(ap.get()) {
    ...
}

如果您确实想从std::shared_ptr<A>获取std::shared_ptr<B>,则可以使用use

In case you actually want to get a std::shared_ptr<B> from the std::shared_ptr<A>, you can use use

std::shared_ptr<B> bp = std::dynamic_pointer_cast<B>(ap);

这篇关于通过shared_ptr进行dynamic_cast吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆