如何使用boost :: smart_ptr在多态性? [英] How to use boost::smart_ptr in polymorphism?

查看:178
本文介绍了如何使用boost :: smart_ptr在多态性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Boost智能指针可用于多态性,但如何

Boost smart pointers can be used with polymorphism, but how do you cast the subclass back to the pointer?

using namespace boost;
// ...
shared_ptr<SuperClass> a_ptr(new SubClass);
// ...
shared_ptr<SubClass> b_ptr = (shared_ptr<SubClass>)a_ptr; // Doesn't compile

最后一行不编译,并给出错误C2440:'type cast':无法从'boost :: shared_ptr < T> '转换为'boost :: shared_ptr < T& c> c>

The last line doesn't compile and gives error C2440: 'type cast' : cannot convert from 'boost::shared_ptr<T>' to 'boost::shared_ptr<T>'

推荐答案

static_pointer_cast

You need to use static_pointer_cast:

struct B { virtual ~B() { } };
struct D : B { };

shared_ptr<B> bp(new D);
shared_ptr<D> dp(static_pointer_cast<D>(b));

(还有 dynamic_pointer_cast const_pointer_cast 分别用于执行动态和常量转换。)

(There are also dynamic_pointer_cast and const_pointer_cast for performing dynamic and const casts respectively.)

这篇关于如何使用boost :: smart_ptr在多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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