我想製作一個複製構造函數,因爲我在我的類中有一個指針。但是,我得到運行時錯誤「調試斷言失敗」,我不知道該怎麼做。我有兩個類,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.請幫助我。謝謝。
這是不夠的代碼爲我們重現錯誤(乍一看看起來正確)。你能給我們一個[最小完整的例子](http://stackoverflow.com/help/mcve)? – Beta
絕對需要一個repro例子。這可能是析構函數,賦值操作符(你也有 - 對嗎?),內存損壞,默認構造函數的問題或其他問題。 –
如果你使用了一個向量,默認的複製構造函數和賦值操作符就可以工作。此外,你的班級不會泄漏內存了。讓C++爲你工作。 –