无法从 'const shared_ptr<base_class>' 转换为 'shared_ptr<derived_class>'

Cannot convert from 'const shared_ptr<base_class>' to 'shared_ptr<derived_class>'

我已声明以下内容vector

vector<shared_ptr<base_class> inventory;

我有以下变量:

shared_ptr<derived_class> equipped_item;

我正在尝试执行以下操作:

equipped_item = inventory[0];

我收到以下错误:

Cannot convert from 'const shared_ptr<base_class>' to 'shared_ptr<derived_class>'

我的问题是为什么不允许我尝试将 equipped_item 设置为 vector 中的所选项目?

由于 base_class 不能隐式转换为 derived_class,因此常规构造函数将不起作用。您应该使用 static_pointer_cast(如果 class 不是多态的)或 dynamic_poiner_cast(如果 class 是多态的):

::std::vector<::std::shared_ptr<base_class>> pointers{::std::make_shared<derived_class>()};
::std::shared_ptr<derived_class> pd{::std::static_pointer_cast<derived_class>(pointers[0])};

请注意,需要从基础 class 转换为派生通常是 class 层次结构不正确或接口使用不正确的标志。

您正在尝试执行以下操作:

pointer_derived =  pointer_base; //No implicit conversion possible.

然而,以下是可能的:

pointer_base = pointer_derived; // Possible.

尝试明确地向下转换你的 pointer_base。

pointer_derived =  static_pointer_cast<Derived>(pointer_base);
//Since you know that pointer_base is pointing to a derived class here.

您正在尝试将 base class 转换为 derived(down-cast), which is not implicitly convertible. In order to do that you need either std::static_pointer_cast (if you are sure about to what you are casting) or std::dynamic_pointer_cast(if the class is polymorphic) as you have used smart pointers.

例如下面是 std::static_pointer_cast 的示例代码:

#include <iostream>
#include <vector>
#include <memory>

class base_class    {};
class derived_class: public base_class {};

int main()
{
    std::shared_ptr<derived_class>  some_derived_ptr = std::make_shared<derived_class>();

    std::vector<std::shared_ptr<base_class>> inventory{some_derived_ptr};

    std::shared_ptr<derived_class>
                equipped_item = std::static_pointer_cast<derived_class>(inventory[0]);
}

cppreferenceshared_ptr转换构造函数从YT"doesn't participate in overload resolution if Y* is not implicitly convertible to T*"。您正在执行从基础到派生的转换,这需要 static_castdynamic_cast,它不是隐式的。

您应该使用 pointer cast,根据您的 class 定义,static_pointer_castdynamic_pointer_cast