创建复制构造函数时调试断言失败



我试图做一个复制构造函数,因为我有一个指针在我的类。然而,我得到了运行时错误"调试断言失败",我不知道该怎么做。我有两个类,MyMatrix和MyImage。我想为MyImage写一个复制构造函数,因此我也为MyMatrix写了一个。

class MyMatrix{
private:
unsigned _width, _height; 
unsigned char *_data;
public:
MyMatrix(MyMatrix &other);
}
MyMatrix::MyMatrix(MyMatrix &other) {
_width = other._width;
_height = other._height;
_data = new unsigned char[_width*_height];
memcpy(_data, other._data, _width*_height*sizeof(unsigned char));
}
class MyImage {
public:
int _width;
int _height;
MyMatrix _Y; //gray level
}
MyImage::MyImage(MyImage &other) {
_width = other._width;
_height = other._height;
_Y = MyMatrix(other._Y);
}
int main(){
    char *filename = "hw1_images/p1/house.raw"; //some raw image
    int width = 512;
int height = 512;
    //read the image
    MyImage inputImage(filename, width, height, fileMode::CFA);
    //copy the image 
    MyImage test(inputImage);
 return 0;
 }

我得到错误,即使我注释memcry()。如果我使用std::cout来显示我的副本的值,它总是221。请帮我一下。谢谢你。

你正在写_Y = MyMatrix(other._Y);,我希望你已经为你的矩阵类定义了赋值运算符:MyMatrix & operator(const MyMatrix & other);否则编译器将为你创建一个默认的,只是复制你的属性,这意味着你的指针将被复制,而不是内容。

并且,当我看到您可以操作一个重要的数据大小时,如果您启用了c++11,我肯定会查看复制交换习惯用法:什么是复制-交换习惯用法?

如果这只是崩溃的问题,那么你可以像下面这样做。

class MyMatrix{
private:
unsigned _width, _height; 
unsigned char *_data;
public:
    MyMatrix(){
    _width = 2;
    _height = 3;
    _data = new unsigned char[sizeof(unsigned char)];
}
MyMatrix(MyMatrix &other);
};
MyMatrix::MyMatrix(MyMatrix &other) {
_width = other._width;
_height = other._height;
_data = new unsigned char[(_width*_height) + 1];
memcpy(_data, other._data, _width*_height*sizeof(unsigned char));
}

相关内容

最新更新