我对c ++ 11指针有疑问。具体来说,如何将基类的唯一指针转换为派生类?
class Base
{
public:
int foo;
}
class Derived : public Base
{
public:
int bar;
}
...
std::unique_ptr<Base> basePointer(new Derived);
// now, how do I access the bar member?
它应该是可能的,但我无法弄清楚如何。每次我尝试使用
basePointer.get()
我最终导致可执行文件崩溃。
提前致谢,我们将不胜感激。
答案 0 :(得分:33)
如果它们是多态类型,并且您只需要指向派生类型的指针,请使用dynamic_cast
:
Derived *derivedPointer = dynamic_cast<Derived*>(basePointer.get());
如果它们不是多态类型,只需要指向派生类型的指针使用static_cast
并希望最好:
Derived *derivedPointer = static_cast<Derived*>(basePointer.get());
如果您需要转换包含多态类型的unique_ptr
:
Derived *tmp = dynamic_cast<Derived*>(basePointer.get());
std::unique_ptr<Derived> derivedPointer;
if(tmp != nullptr)
{
basePointer.release();
derivedPointer.reset(tmp);
}
如果您需要转换包含非多态类型的unique_ptr
:
std::unique_ptr<Derived>
derivedPointer(static_cast<Derived*>(basePointer.release()));