Matrix::Matrix(int _row, int _col): row(_row), col(_col) {
matrix = new double*[row];
for (int i = 0; i < row; ++i) {
matrix[i] = new double[col];
}
}
Matrix::Matrix(const Matrix& m): row(m.row), col(m.col) {
matrix = new double*[row];
for (int i = 0; i < row; ++i) {
matrix[i] = new double[col];
for (int j = 0; j < col; ++j) {
matrix[i][j] = m.matrix[i][j];
}
}
}
Matrix& Matrix::operator=(const Matrix& m) {
row = m.row;
col = m.col;
matrix = new double*[row];
for (int i = 0; i < row; ++i) {
matrix[i] = new double[col];
for (int j = 0; j < col; ++j) {
matrix[i][j] = m.matrix[i][j];
}
}
return *this;
}
Matrix::~Matrix() {
for (int i = 0; i < row; ++i) {
delete[] matrix[i];
}
delete[] matrix;
}
// 这个操作符重载这样写可以吗?//确实泄露了。。。我明白了
Matrix& Matrix::operator*(const Matrix& m) {
Maples::assert((col == m.row), "Matrix Col != Row Error!");
Matrix* result = new Matrix(row, m.col);
double temp;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < m.col; ++j) {
temp = 0;
for (int k = 0; k < col; ++k) {
temp += (matrix[i][k] * m.matrix[k][j]);
}
result->matrix[i][j] = temp;
}
}
return *result;
}
operator= 你沒有對之前分配的空間 進行 處理 ,可能 洩漏
operator* 要返回 Matrix,不要new了然後返回,這樣很可能會內存洩漏,例如:
呼叫者忘記了釋放;呼叫者沒有接收回傳值;