2015-09-07 40 views
0

我想製作一個複製構造函數,因爲我在我的類中有一個指針。但是,我得到運行時錯誤「調試斷言失敗」,我不知道該怎麼做。我有兩個類,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.請幫助我。謝謝。

+3

這是不夠的代碼爲我們重現錯誤(乍一看看起來正確)。你能給我們一個[最小完整的例子](http://stackoverflow.com/help/mcve)? – Beta

+0

絕對需要一個repro例子。這可能是析構函數,賦值操作符(你也有 - 對嗎?),內存損壞,默認構造函數的問題或其他問題。 –

+0

如果你使用了一個向量,默認的複製構造函數和賦值操作符就可以工作。此外,你的班級不會泄漏內存了。讓C++爲你工作。 –

回答

0

你正在寫_Y = MyMatrix(other._Y);,我希望您已經定義了assignement運營商的Matrix類:MyMatrix & operator(const MyMatrix & other);否則編譯器會創建一個默認的一個你,只要複製的屬性,這意味着你的指針將被複制,而不是內容。

而且,我看你能處理數據的重要大小,如果你有C++ 11允許,我肯定會看看副本交換成語:What is the copy-and-swap idiom?

+0

非常感謝。 – HemHem

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