6

Boost 智能指针可以与多态一起使用,但是如何将子类转换回指针呢?

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

最后一行没有编译并给出error C2440: 'type cast' : cannot convert from 'boost::shared_ptr<T>' to 'boost::shared_ptr<T>'

4

1 回答 1

12

您需要使用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_castconst_pointer_cast分别用于执行动态和常量转换。)

于 2011-01-21T22:19:24.440 回答