【发布时间】:2013-02-06 22:38:10
【问题描述】:
我有一个用于神经网络程序和重载算术运算符的定制矩阵库。 这是类声明:
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的是垃圾指针..
请给我一些建议...
【问题讨论】:
-
当然是销毁了,c++就是这样工作的。您是否在复制构造函数和赋值运算符中实现了深层复制?并显示你的构造函数/析构函数。
-
考虑使用vector,而不是使用
double ** mat。这里的优点是您可以使用简单的复制构造函数。
标签: c++ matrix operator-overloading