【发布时间】:2014-10-05 01:05:32
【问题描述】:
简而言之,我的任务是创建一个动态分配内存以形成 int 值矩阵的类。
类的一部分是执行基本矩阵计算的成员函数——加法、减法和乘法。一切都可以编译(至少在我这边),但是当我使用驱动程序测试乘法部分时,它一直在崩溃。
我将 Codeblocks 用作我的 IDE,但调试器在尝试解决问题时运气不佳。计算似乎完成了(使用正确的值),但随后某处出现了可怕的错误。
为清楚起见,Matrix 类的每个对象都有以下成员数据:
private:
int rows;
int cols;
int **element;
下面是实现文件的 sn-p,其中充实了重载的 operator*。在执行乘法的循环之前将 temp.element[i][x] 设置为 '0' 的部分被注释掉,因为默认构造函数已经将所有值设置为 '0' - 我在放入时忘记了起初。当我也没有注释掉它时它也不起作用。
在测试中,我使用了一个 2x3 数组和一个 3x2 数组。
Matrix Matrix::operator*(const Matrix &aMatrix) const
{
if(cols == aMatrix.rows)
{
Matrix temp(rows, aMatrix.cols);
for(int i = 0; i < rows; i++)
{
for(int x = 0; x < aMatrix.cols; x++)
{
//temp.element[i][x] = 0;
for(int n = 0; n < cols; n++)
{
temp.element[i][x] += (element[i][n]
* aMatrix.element[n][x]);
}
}
}
return temp;
}
else
{
cerr << "Matrix multiplication failed -- incompatible matrix sizes."
<< endl;
return *this;
}
}
在尝试检查代码并发现错误后,我开始重新检查我拥有的其他功能。看起来加法和减法都有效,但如果矩阵不兼容(即尝试添加 2x3 和 4x4),程序将关闭。
下面是加法的 sn-p(减法几乎相同,只是在最后的循环中使用 '-' 而不是 '+'。
Matrix Matrix::operator+(const Matrix &aMatrix) const
{
if(rows == aMatrix.rows && cols == aMatrix.cols)
{
Matrix temp(rows, cols);
for(int i = 0; i < rows; i++)
{
for(int x = 0; x < cols; x++)
{
temp.element[i][x] = element[i][x] + aMatrix.element[i][x];
}
}
return temp;
}
else
{
cerr << "Undefined matrix addition -- matrices are different sizes."
<< endl;
return *this;
}
}
感谢任何帮助或见解。谢谢。
已编辑:添加了重载赋值运算符、复制构造函数和析构函数代码。
下面是重载的赋值运算符:
Matrix Matrix::operator=(Matrix aMatrix)
{
if(this != &aMatrix)
{
for(int i = 0; i < rows; i++)
{
delete [] element[i];
element[i] = NULL;
}
delete [] element;
rows = aMatrix.rows;
cols = aMatrix.cols;
element = new int* [rows];
for(int i = 0; i < rows; i++)
{
element[i] = new int [cols];
for (int x = 0; x < cols; x++)
{
element[i][x] = aMatrix.element[i][x];
}
}
}
return *this;
}
下面是复制构造函数:
Matrix::Matrix(const Matrix &aMatrix)
{
rows = aMatrix.rows;
cols = aMatrix.cols;
element = new int* [rows];
for(int i = 0; i < rows; i++)
{
element[i] = new int [cols];
for (int x = 0; x < cols; x++)
{
element[i][x] = aMatrix.element[i][x];
}
}
}
析构函数:
Matrix::~Matrix()
{
for(int i = 0; i < rows; i++)
{
delete [] element[i];
element[i] = NULL:
}
delete [] element;
element = NULL;
}
【问题讨论】:
-
如何为
element分配内存?你不应该在做任何算术之前检查尺寸吗? -
在默认构造函数中动态分配。我用动态内存分配标记了这个问题,但没有包括>_
-
@uber08 - 您正在按值返回一个矩阵。这意味着我们需要查看您的
Matrix用户定义的复制构造函数、赋值运算符和析构函数。它们都在您发布的代码中发挥了重要作用。 -
@uber08 -
Matrix Matrix::operator=(Matrix aMatrix)你应该通过 const 引用而不是值来传递。此外,您应该返回一个引用,而不是一个全新的对象。它有很多错误,并且会导致问题。 -
我无法想象在错误条件下返回操作的 lhs 的充分理由。客户端代码很可能注定了标准错误上的各种错误计算和相应的错误消息。实际上,假设库拥有标准错误对于客户端的开发人员来说可能是痛苦的。也许他们对标准错误有特定的想法。也许他们将其重定向到 /dev/null 之类的东西。
标签: c++ multidimensional-array matrix-multiplication dynamic-memory-allocation