<derived> 从函数返回时如何从shared_ptr转换为shared_ptr<base>?

How do you convert from shared_ptr<derived> to shared_ptr<base> when returning from a function?

本文关键字:shared ptr lt gt 转换 base derived 函数 返回      更新时间:2023-10-16

假设我们有一个抽象类Vehicle。一堆类将继承自Vehicle,如Boat, Car, Truck等。

我想创建一个函数,该函数返回给我一个指向给定参数的车辆的指针,我传入。我不需要访问底层车辆。到目前为止,我有这样的东西:

boost::shared_ptr<Vehicle> create_vehicle(Environment e, Cost c) {
    if (e.is_water()) {
        boost::shared_ptr<Boat> boat(new Boat());
        boat->set_location("USA");
        boat->set_environment(e);
        ...
        return boat; // How should I return the shared pointer here?
                     // I get an error for doing this 
                     // "Vehicle is an inaccessible base of boat"
    } else if (e.is_land()) {
        ...
    }
}

当函数的返回值是shared_ptr时,我如何返回派生的shared_ptr?铸造是必要的还是有办法不铸造?我想我也可以按值返回派生类,但我不想在返回时制作另一个车辆副本。

从您的错误消息显示您在VehicleBoat之间使用了私有或受保护的继承,而不是公共继承。

您需要使用static_pointer_cast -它在某种程度上相当于shared_pointer的static_cast。看看http://www.boost.org/doc/libs/1_55_0/libs/smart_ptr/shared_ptr.htm#functions

你可以为Vehicle创建一个shared_ptr并使用它

boost::shared_ptr<Vehicle> create_vehicle(Environment e, Cost c) 
{
    boost::shared_ptr<Vehicle> vehicle;
    if (e.is_water()) {
        Boat *boat = new Boat();
        boat->set_location("USA");
        boat->set_environment(e);
        vehicle.reset(boat); // Assign the pointer to the result
    } else if (e.is_land()) {
        ...
    }
    return vehicle;
}