指向从基类派生类的std :: unique_ptr的指针

问题描述 投票:0回答:1

我正在尝试制作一个可以指向任何std::unique_ptr<BaseClass>*std::unique_ptr<DerivedClass>

我具有以下类层次结构:

[InputHandler] <--inherits from-- [DrawingTool] <--inherits from-- [ToolName]

以及以下代码:

std::unique_ptr<DrawingTool> *active_tool;
active_tool = tool_manager.getCurTool();   // Returns a unique_ptr<DrawingTool>*

std::unique_ptr<InputHandler> *cur_input_handler = active_tool;

但是这会导致错误:

 error: cannot convert ‘std::unique_ptr<DrawingTool>*’ to ‘std::unique_ptr<InputHandler>*’ in initialization

我该如何进行这项工作?

c++ pointers polymorphism smart-pointers c++-standard-library
1个回答
1
投票

如果要引用代码其他位置拥有的对象,则可以使用std::shared_ptr(至少要实现示例中所显示的内容,这是问题的一部分)。然后,如果要将基类std::shared_ptr转换为派生类std::shared_ptr,则可以执行以下操作:

© www.soinside.com 2019 - 2024. All rights reserved.