2 次元行列でいくつかの操作を実行しようとしています。計算を行うために (+ 、 - 、および *) をオーバーロードしました。私は(私が信じている)メモリ管理に関して問題があります。次のコードを見てください。
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;
}