调试断言在制作复制构造函数时失败

时间:2015-09-07 03:38:46

标签: c++

我正在尝试创建一个复制构造函数,因为我的类中有一个指针。但是,我收到运行时错误“Debug Assertion failed”,我不知道该怎么做。我有两个分类,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。请帮助我。谢谢。

2 个答案:

答案 0 :(得分:0)

如果它只是崩溃的问题,那么你可能会做类似下面的事情。

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));
}

答案 1 :(得分:0)

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

而且,我看到你可以操作一个重要的数据大小,如果你启用了c ++ 11,我肯定会看看复制交换习语:What is the copy-and-swap idiom?