我正在尝试在二维矩阵中进行一些操作。我重载了 (+ , - 和 *) 来进行计算。我有一个关于(我相信)内存管理的问题。看下面的代码:
Mtx M1(rows1,cols1,1.0); //call the constructor
Mtx M2(rows2,cols2,2.0); //call the constructor
Mtx M3(rows3,cols3,0.0); //call the constructor
M3 = M1 + M2;
cout << M3 << endl;
Mtx Mtx::operator+(const Mtx &rhs)
{
double **ETS;
ETS = new double*[nrows];
for (int i = 0; i < rhs.nrows; i++) {
ETS[i] = new double[rhs.ncols];
}
if (ETS == NULL) {
cout << "Error Allocation on the Heap" << endl;
exit(1);
}
for (int i = 0; i < rhs.nrows; i++) {
for (int j = 0; j < rhs.ncols; j++) {
ETS[i][j] = 0.0;
}
}
for (int i = 0; i < rhs.nrows; i++) {
for (int j = 0; j < rhs.ncols; j++) {
ETS[i][j] = ets[i][j];
}
}
for (int i = 0; i < rhs.nrows; i++) {
for (int j = 0; j < rhs.ncols; j++) {
ETS[i][j] = ETS[i][j] + rhs.ets[i][j];
}
}
Mtx S(nrows, ncols, ETS);
delete [] ETS;
return S;
}
我想我的问题在这里:
Mtx S(nrows, ncols, ETS);
delete [] ETS;
return S;
这是返回的正确方法ETS
吗?还是您认为问题出在构造函数上?当我执行上述返回时,我没有得到任何输出!
这是构造函数Mtx S(nrows, ncols, ETS);
Mtx::Mtx(int rows, int cols, double **ETS)
{
ets = new double*[nrows];
for (int i = 0; i < nrows; i++) {
ets[i] = new double[ncols];
}
for (int i = 0; i < nrows; i++) {
for (int j = 0; j < ncols; j++) {
ets[i][j] = ETS[i][j];
}
}
}
我的复制构造函数:
Mtx::Mtx(const Mtx& rhs)
:nrows(rhs.nrows), ncols(rhs.ncols)
{
ets = new double*[nrows];
for (int i = 0; i < nrows; i++) {
ets[i] = new double[ncols];
}
for (int i = 0; i < rhs.nrows; i++) {
for (int j = 0; j < rhs.ncols; j++) {
ets[i][j] = rhs.ets[i][j];
}
}
}
我超载<<
打印M3
。它工作正常,因为我测试了打印M1
和M2
.
我也做了以下,但仍然没有工作:
Mtx S(nrows, ncols, ETS);
for (int i = 0; i < rhs.nrows; i++) {
delete [] ETS[i];
}
delete [] ETS;
return S;
}