jan8705 于 2013.06.14 23:46 提问

//Matrix.h
class Matrix
{
public:
Matrix();
~Matrix();
Matrix(int,double*); //矩阵行列数、数组指针
Matrix operator+(const Matrix&);//矩阵相加
friend ostream& operator<<(ostream&,const Matrix&);//
private:
int n; //矩阵的行列数
double* pt;
};

//Matrix.cpp
Matrix::Matrix():pt(0)
{
n = 0;
}
Matrix::Matrix(int r,double* p): n(r)
{

pt = new double[r*r];
for(int i=0; i<r*r;i++)

pt[i] = p[i];

}
Matrix::~Matrix()
{
delete []pt;
pt = 0;
}
//矩阵相加函数实现
Matrix Matrix::operator+(const Matrix& m)
{
for(int i=0;i<n*n;i++)

pt[i] = pt[i] + m.pt[i];

return *this;
}
//矩阵输出函数的实现
ostream& operator<<(ostream& output,const Matrix& m)
{

for(int i=0;i<m.n*m.n;i++)

{

if((i+1)%m.n == 0)

output<<m.pt[i]<<endl;

else

output<<m.pt[i]<<" ";

}

``````return output;
``````

}

double *p1,*p2,x,y;
int n;

``````cout<<"请输两个矩阵的行列数(n*n):"<<endl<<"n=";
cin>>n;

cout<<"请输入第一个矩阵m1的元素:"<<endl;

p1=(double *)malloc(sizeof(double)*n*n);
for(int i=0;i<n*n;i++)
{
cin>>x;
p1[i]=x;
}

cout<<"请输入第二个矩阵m2的元素:"<<endl;
p2=(double*)malloc(n*n*sizeof(double));
for(int j=0;j<n*n;j++)
{
cin>>y;
p2[j]=y;
}

Matrix m1(n,p1),m2(n,p2),M;
M=m1+m2;
cout<<"m1+m2:"<<endl;
cout<<M<<endl;
free(p1);
free(p2);
return 0;
``````

2个回答

fanxu1986   2015.01.21 21:12

tlxzsz   2014.02.17 19:37

delete []pt;换成delete pt；试试。