繁体   English   中英

没有合适的用户定义的继承类转换

[英]No suitable user-defined conversion with inherited classes

我正在努力将子类作为超类存储在超级 class 指针的向量中。 目标是拥有一个 ContainerObjects 向量,它可以是 bin 和 box。

这是一个准系统示例 - 在我的代码中,我传递了要存储在盒子中的东西的定义,然后将盒子添加到我的库存中。 那部分工作正常,但将盒子添加到库存中让我失望。

typedef std::unique_ptr<ContainerObject> U_ContainerObjectPtr;
typedef std::unique_ptr<Box> U_BoxPtr;
typedef std::unique_ptr<Bin> U_BinPtr;

class DoingWork
{
private:
  StorageArea area;
public:
  void boxItem( ItemData data)
  {
    U_BoxPtr newBox = std::make_unique<Box>(data);  
    area.addContainer( newBox );
  }
}


class StorageArea
{
  vector<U_ContainerObjectPtr> myStorageArea;

  addContainer( U_ContainerObjectPtr container)
  {
    myStorageArea.push_back(container);  
  }
}

class ContainerObject
{
}

class Box : ContainerObject
{
  Box( ItemData data)
{
  // store the data in the box
}
}

// Another container type
class Bin : ContainerObject
{
}

我得到的错误是在 boxItem() 中调用 addContainer() 时出现“没有合适的用户定义的从 U_BoxPtr 到 U_ContainerObjectPtr 的转换”,这是可以理解的。 我不确定我需要做什么来解决这个问题,或者即使这实际上是可能的。

C++ 也是相当新的。

首先,您应该公开您的 inheritance。

class Box: ContainerObject -> class Box: public ContainerObject

class Bin: ContainerObject -> class Bin: public ContainerObject

其次, std::unique_ptr意味着只有一个所有者,所以它没有复制构造函数/赋值,只有移动构造函数/赋值。 所以你应该做以下替换:

area.addContainer(newBox); -> area.addContainer(std::move(newBox));

myStorageArea.push_back(container); -> myStorageArea.push_back(std::move(container));

整个代码如下所示:

#include <memory>
#include <vector>

struct ItemData
{
};

class ContainerObject
{
};

using U_ContainerObjectPtr = std::unique_ptr<ContainerObject>;

class Box : public ContainerObject
{
public:
    Box(ItemData data)
    {
        // store the data in the box
    }
};

// Another container type
class Bin : public ContainerObject
{
};

using U_BoxPtr = std::unique_ptr<Box>;
using U_BinPtr = std::unique_ptr<Bin>;

class StorageArea
{
    std::vector<U_ContainerObjectPtr> myStorageArea;

public:
    void addContainer(U_ContainerObjectPtr container)
    {
        myStorageArea.push_back(std::move(container));
    }
};

class DoingWork
{
private:
    StorageArea area;

public:
    void boxItem(ItemData data)
    {
        U_BoxPtr newBox = std::make_unique<Box>(data);
        area.addContainer(std::move(newBox));
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM