复制构造函数和赋值运算符有问题。编写了乘法矩阵的代码:
Matrix& Matrix::operator * (const Matrix &second) const
{
// Create result matrix
Matrix result(Rows(), second.Columns());
// Multiply matricies
for (unsigned i = 0; i < Rows(); i++)
{
for (unsigned j = 0; j < second.Columns(); j++)
{
result[i][j] = 0.0;
for (unsigned k = 0; k < Columns(); k++)
{
result[i][j] += m_matrix[i][k] * second[k][j];
}
}
}
return result;
}
在主代码中,我调用操作员:
Matrix C = A * B;
然而代码在赋值之前破坏了结果变量,如何正确编写这样的代码来返回结果矩阵?复制构造函数是:
Matrix::Matrix(const Matrix& matrix)
{
AllocateMatrixArray(matrix.Rows(), matrix.Columns());
CopyMatrixData(matrix);
}
赋值运算符是:
Matrix& Matrix::operator = (const Matrix& other)
{
AllocateMatrixArray(other.Rows(), other.Columns());
CopyMatrixData(other);
return *this;
}
但是我看到编译器不使用它 - 复制构造函数就足够了。