重载操作符
我定义了矩阵类如下,重载了+法操作,但是问题如注释所示,应该怎么改呢:
template<class T>
class Matrix
{
private:
unsigned rows;
unsigned cols;
T **p;
public:
Matrix():rows(0),cols(0){p=NULL;}
Matrix(unsigned r,unsigned c);
~Matrix();
Matrix<T> Reverse(); //矩阵转置
T* operator [](unsigned i); //矩阵的下标访问
Matrix<T> operator +(const Matrix<T> &a); //矩阵相加
Matrix<T> operator *(const Matrix<T> &a); //矩阵相乘
Matrix<T> operator =(const Matrix<T> &a); //矩阵赋值
template <class Type > friend ostream& operator <<(ostream & os,const Matrix<Type> & a); //重载输出操作符
};
template <class T>
Matrix<T> Matrix<T>:: operator +(const Matrix<T> &a)
{
if(rows==a.rows && cols==a.cols)
{
Matrix<T> matrix(a.rows,a.cols);
for(int i=0;i<matrix.rows;i++)
for(int j=0;j<matrix.cols;j++)
{
matrix.p[i][j]=(a.p[i][j])+p[i][j];
}
return matrix; //返回局部对象matrix,而matrix有指针成员,一旦退出函数,会调用matrix的析
//构函数从而释放指针成员占的内存,进而导致错误,请问我应该怎么改,或者有其他更好的实现,希望能给出代码,谢谢
}
}