【问题标题】:How to create an array with Object that has private copy constructor如何使用具有私有复制构造函数的对象创建数组
【发布时间】:2021-03-05 01:52:16
【问题描述】:

我有一个包含一些成员的结构和一个具有私有复制构造函数的对象,我如何创建一个包含该对象的数组。 例如: 我有一个对象:

class Image
{
   ...
   private:
      Image(const Image&);
      Image& operator=(const Image&);
      u8* pixel;
      int width;
      int height
}

struct ImageInformation
{
   Image image;
   int resolution;
}

我想为 ImageInformation 创建一个数组:向量,但这是禁止的

【问题讨论】:

  • 您是在尝试创建 C 样式数组、std::array 还是 std::vector?也许提供更多代码,包括触发错误的行?
  • 哪些构造函数是公共的?
  • std::vectroremplace 函数应该是你想要的。

标签: c++ private-constructor


【解决方案1】:

您必须在Image class 上定义move ctormove assignment operator,因为您提供了一个声明为copy ctorcopy assignment operator 的用户,因此将删除默认实现。

然后您应该可以毫无问题地使用vector

class Image
{
public:
    Image( int height, int width ) 
        : height_{ height }
        , width_{ width }
    { }

    Image( Image&& ) = default;
    Image& operator=( Image&& ) = default;

    Image( const Image& ) = delete;
    Image& operator=( const Image& ) = delete;

private:
    int height_;
    int width_;
};

class ImageInformation
{
public:
    explicit ImageInformation( Image image )
        : image_{ std::move( image ) }
    { }

private:
    Image image_;
};


int main( )
{
    std::vector<ImageInformation> containers;

    Image image{ 10, 10 };
    containers.emplace_back( std::move( image ) );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多