gpt4 book ai didi

c++ - 具有多重继承的 shared_ptr 转换

转载 作者:行者123 更新时间:2023-11-30 02:21:12 25 4
gpt4 key购买 nike

我有点糊涂了。

namespace Io
{
class IDevice;
}

//...

namespace Sensor
{
class IDevice;
}

//...

class ComplexDeviceHandler : public Io::IDevice, public Sensor::IDevice;

//...

std::vector<std::shared_ptr<Io::IDevice>> devices; //populated by objects of type ComplexDeviceHandler

//..

for (const auto& device : devices)
{
std::shared_ptr<Sensor::IDevice> sensor = device; //obviously, error here
}

两者都是 Io::IDeviceSensor::IDevice是接口(interface)(某种程度上)。我应该使用什么转换来转换 std::shared_ptr<Io::IDevice>std::shared_ptr<Sensor::IDevice> .在这种情况下,std::shared_ptr<Io::IDevice>存储 ComplexDeviceHandler 类型对象的地址,它是两种类型的 child 。

最佳答案

您需要先尝试将其转换为 ComplexDeviceHandler*,检查它是否有效,然后将其转换为 Sensor::IDevice*:

for (const auto& device: devices)
{
if (auto sidptr = std::dynamic_pointer_cast<ComplexDeviceHandler>(device)) {
std::shared_ptr<Sensor::IDevice> sensor = sidptr;
}
}

关于c++ - 具有多重继承的 shared_ptr 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48810732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com