如何在多态性中使用boost :: smart_ptr?
-
16-10-2019 - |
题
增强智能指针 可以与多态性一起使用, ,但是如何将子类送回指针?
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_cast
和 const_pointer_cast
分别进行动态和const铸造。)
不隶属于 StackOverflow