重載
Matrix& Matrix::operator-(const Matrix &m) {
if (m.row_n != row_n||m.column_n != column_n) {
std::cout << "Size not matching, can\'t add!" << std::endl;
std::cout << "the left is returned" << std::endl;
return this;
}
static Matrix temp(row_n, column_n); //這裡這個分配的內存什麼時候刪除?
temp.name = 'f';
for (int i = 0; i < row_n; i++) {
for (int j = 0; j < column_n; j++) {
temp.element[i][j] = element[i][j] - m.element[i][j];
}
}
return temp;
}
構造函數::
Matrix::Matrix() {
row_n = 2;
column_n = 2;
element = ( int *)new int* [2];
for (int i = 0; i < 2; i++) {
element[i] = new int2;
element[i][i] = 1;
}
row_n = 2;
column_n = 2;
}
重載
Matrix& Matrix::operator=(const Matrix &mp) {
row_n = mp.row_n;
column_n = mp.column_n;
for (int i = 0; i < row_n; i++) {
delete[] element[i];
}
delete[] element;
element = (int **)new int*[mp.row_n];
for (int i = 0; i < column_n; i++)
element[i] = new int[mp.column_n];
for (int i = 0; i < row_n; i++)
for (int j = 0; j < column_n; j++)
element[i][j] = mp.element[i][j];
return *this;
}
使用::
Matrix ma1, temp;
temp = ma1 - ma5;
錯誤::
*** Error in `./temp': double free or corruption (out): 0x0000000000f62090 ***
已放棄 (核心已轉儲)
一直找不到原因,希望高手能指點一下
double free就是你的代碼有多次重復是否同一個指針。
operator中沒必要是否mp的指針,而是的放到析構函數中。