复制构造函数和重载赋值运算符的困难

问题描述 投票:0回答:1

我正在解决一个问题,请打开一个PGM文件,制作两个副本,修改原始文件,然后分别保存所有三个文件。我在理解如何编写一个接受数组并包含重载赋值运算符的副本构造函数时遇到很多麻烦。我还需要包含一个析构函数,以便遵循三个定律,但是到目前为止,我所做的每个迭代都会给我一个堆损坏的错误。

截至目前,我的代码修改了原始文件并将其很好地导出。但是我的两个未修改副本的输出文件只包含一个三个零,另一个包含前三行。

PGMImage::PGMImage(const PGMImage & anotherImage) {
  int i;
  pixels = new int[numberPixels + 1];
  for (i = 0; i < numberPixels; ++i) {
    pixels[i] = anotherImage.pixels[i];
  }
  cout << "Copy constructor called." << endl;
}

//Overloaded Assignment Operator
PGMImage & PGMImage::operator = (const PGMImage & anotherImage) {
  if (this != & anotherImage) {
    //delete pixels;                  
    pixels = new int[numberPixels];

    * pixels = * (anotherImage.pixels);
  }
  return *this;
}

//Destructor
PGMImage::~PGMImage() {}
c++ operator-overloading copy-constructor
1个回答
0
投票

我假设int* pixelsint numberPixels是您班上代表图像数据的私有成员。我还要大胆猜测您是否拥有PGMImage的其他成员,例如widthheightbitdepth。赋值运算符和复制构造函数都需要将所有成员变量复制到目标对象。

而且,我不知道您为什么要对内存分配执行+1

为了清楚起见,我仅使用this->来指示目标对象上的成员并将其与anotherImage区分开。

我认为您的方法应该像这样:

void PGMImage::InitializeFromImage(const PGMImage& anotherImage) {
  this->pixels = new int[anotherImage.numberPixels];
  memcpy(this->pixels, anotherImage.pixels, sizeof(int)*anotherImage.numberPixels);
  this->numberPixels = anotherImage.numberPixels;

  this->width = anotherImage.width;
  this->height = anotherImage.height;
  this->bitdepth = anotherImage.bitdepth;
}

PGMImage::PGMImage(const PGMImage& anotherImage) {
  InitializeFromImage(anotherImage);
  cout << "Copy constructor called." << endl;
}

PGMImage& PGMImage::operator = (const PGMImage &anotherImage) {
  if (this != &anotherImage) {
      delete [] this->pixels;
      this->pixels = nullptr;
      InitializeFromImage(anotherImage);
  }
  return *this;
}
© www.soinside.com 2019 - 2024. All rights reserved.