我有一个用于神经网络程序和重载算术运算符的定制矩阵库。
这是类声明:
class Matrix{
public:
int m;
int n;
double **mat;
Matrix(int,int);
Matrix(int);
Matrix(const Matrix& that):mat(that.mat),m(that.m),n(that.n)
{
mat = new double*[m];
for(int i = 0;i<m;i++)mat[i] = new double[n];
};
~Matrix();
friend istream& operator>>(istream &in, Matrix &c);
friend ostream& operator<<(ostream &out, Matrix &c);
Matrix operator+(const Matrix& other);
};
这是 + 运算的函数定义:
Matrix Matrix::operator+(const Matrix& other)
{
Matrix c(m,n);
for(int i=0;i<m;i++)
{
for(int j = 0; j<n;j++)
c.mat[i][j] = mat[i][j] + other.mat[i][j];
}
return c;
}
我尝试以各种方式实现它,但错误是相同的......这是一个例子
Matrix x(m,n); //m and n are known
x = a+b; // a and b are also m by n matrices
我已经使用断点调试了代码,这是错误......运算符函数中的局部矩阵“c”在返回之前被破坏因此分配给 x 的是一个垃圾指针。
请给我建议一些东西...
您需要为您的类定义一个复制构造函数。复制构造函数需要分配内存mat
并复制数据。
如果没有这个,当你return c
,构造一个具有相同值的新对象mat
as c
. When c
随后超出范围,它会删除c.mat
。结果,副本c
留下一个悬空指针。
完成此操作后,您还应该实现一个赋值运算符。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)