[英]Cannot convert unique_ptr<derived> to unique_ptr<base>
[英]convert base class unique_ptr to derived class unique_ptr
我需要将我的基类unique_ptr
转换为派生类unique_ptr
以便我可以访问派生类的一些功能。
我的代码抛出错误。 这里发生了什么问题?
#include <iostream>
#include <memory>
class Base
{};
class Derived : public Base
{
public:
Derived(int x):_x(x){}
int oneDerivedClassFunction()
{ return _x; }
private:
int _x;
};
int main()
{
std::unique_ptr<Base> basePtr;
basePtr.reset(new Derived(10));
auto der = std::unique_ptr<Derived>(dynamic_cast<Derived*>(basePtr.release())); // error here!
printf("%d", der->oneDerivedClassFunction());
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.