增强智能指针 可以与多态性一起使用, ,但是如何将子类送回指针?

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>'

有帮助吗?

解决方案

您需要使用 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 分别进行动态和const铸造。)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top