我正在编写一些用于自学C ++的代码。
以下代码:
#include <iostream>
using namespace std;
class Matrix
{
int m, n;
public:
float** value;
Matrix(int m, int n)
{
value = new float*[m];
for (int i = 0; i < m; ++i)
value[i] = new float[n];
this->m = m; this->n = n;
}
~Matrix()
{
for (int i = 0; i < m; ++i)
delete[] value[i];
delete[] value;
}
Matrix(const Matrix& A)
{
m = A.getLength();
n = A.getWidth();
value = new float*[m];
for (int i = 0; i < m; ++i)
value[i] = new float[n];
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
value[i][j] = A.value[i][j];
}
int getLength(void) const
{
return m;
}
int getWidth(void) const
{
return n;
}
void print() const
{
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
cout << value[i][j] << "\t";
cout << endl;
}
}
Matrix operator + (const Matrix& B)
{
if (m != B.getLength() || n != B.getWidth())
return Matrix(0, 0);
Matrix C = Matrix(m, n);
cout << value << endl;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
C.value[i][j] = value[i][j] + B.value[i][j];
return C;
}
void operator = (const Matrix& A)
{
m = A.getLength();
n = A.getWidth();
value = new float*[m];
for (int i = 0; i < m; ++i)
value[i] = new float[n];
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
value[i][j] = A.value[i][j];
}
};
int main()
{
Matrix A = Matrix(3, 3);
A.value[0][0] = 1; A.value[0][1] = 2; A.value[0][2] = 3;
A.value[1][0] = 4; A.value[1][1] = 5; A.value[1][2] = 6;
A.value[2][0] = 7; A.value[2][1] = 8; A.value[2][2] = 9;
Matrix B = Matrix (3, 3);
B.value[0][0] = 1; B.value[0][1] = 2; B.value[0][2] = 3;
B.value[1][0] = 4; B.value[1][1] = 5; B.value[1][2] = 6;
B.value[2][0] = 7; B.value[2][1] = 8; B.value[2][2] = 9;
Matrix C = A + B;
cout << C.value << endl;
C.print();
return 0;
}
在“Matrix C = A + B”部分产生内存泄漏?我不知道在关联完成后是否销毁了返回的矩阵。如果是的话,有没有办法解决它?
答案 0 :(得分:0)
声明
Matrix C = A + B;
没有泄漏。
尽管在代码中未使用复制赋值运算符,但复制赋值运算符不会释放先前分配给对象矩阵的内存。 复制赋值运算符与复制构造函数的不同之处在于,对象已经创建并具有已分配的矩阵。您还必须检查是否有自我分配。
此外,它应声明为
Matrix & operator = (const Matrix& A)
至于operator +
,则应将其声明为
Matrix operator + (const Matrix& B) const;
或
const Matrix operator + (const Matrix& B) const;