我正在尝试在二维矩阵中进行一些操作。我超载了(+,-和*)进行计算。我有一个关于(我相信)内存管理的问题。看下面的代码:

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。它工作正常,因为我测试了打印M1M2

我还执行了以下操作,但仍无法正常工作:

Mtx S(nrows, ncols, ETS);
for (int i = 0; i < rhs.nrows; i++) {
    delete [] ETS[i];
}
delete [] ETS;
return S;
}

最佳答案

您可以改用

std::vector< std::vector<double> >


代替

double **


就范围而言,这将更加安全。而且你只需要使用功能

std::vector::size()




std::vector::clear()


在析构函数中。 :)

关于c++ - C++中的二维矩阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11597513/

10-11 18:06