#include <iostream.h>
#include <stdlib.h>
class Matrix
{
int *p;
int row,col;
public:
Matrix(){row=col=0;p=NULL; }
Matrix(int,int);
void show();
void operator =(Matrix &m);
friend Matrix& operator +(Matrix &m1,Matrix &m2);
friend Matrix& operator -(Matrix &m1,Matrix &m2);
friend Matrix& operator *(Matrix &m1,Matrix &m2);
void transf();
~Matrix()
{
if (p) { delete []p;p=NULL; }
}
};
Matrix::Matrix(int m,int n)
{
int i,j,x;
if (m<=0 || n<=0)
{
cout<<"矩阵行、列数错误!\n";
row=col=0;
p=NULL;
}
else
{
row=m;col=n;
p=new int[row*col];
cout<<"创建矩阵对象:\n";
for (i=0;i<row;i++)
{
cout<<"请输入矩阵的第"<<i+1<<"行"<<col<<"个元素值:";
for (j=0;j<col;j++)
cin>>x,*(p+i*col+j)=x;
}
}
}
void Matrix::show()
{
int i,j;
if (p)
{
for (i=0;i<row;i++)
{
for (j=0;j<col;j++)
cout<<*(p+i*col+j)<<'\t';
cout<<endl;
}
}
}
void Matrix::operator =(Matrix &m)
{
if (p) delete[] p;
int i,k=m.row*m.col;
if (k>0)
{
p=new int[k];
for (i=0;i<k;i++)
p[i]=m.p[i];
row=m.row;
col=m.col;
}
else { p=NULL;row=col=0; }
}
Matrix& operator +(Matrix &m1,Matrix &m2)
{
static Matrix temp;
if (m1.row!=m2.row || m1.col!=m2.col)
{
cout<<"两矩阵不能相加!\n";
return temp;
}
int i,k=m1.row*m1.col;
if (k>0)
{
int *s;
s=new int[k];
for(i=0;i<k;i++)
s[i]=m1.p[i]+m2.p[i];
temp.p=s;
temp.row=m1.row;
temp.col=m1.col;
return temp;
}
return temp;
}
Matrix& operator -(Matrix &m1,Matrix &m2)
{
//请完成此函数的设计
}
Matrix& operator *(Matrix &m1,Matrix &m2)
{
static Matrix t;
int i,j,m,n,k;
m=m1.row;
n=m2.col;
if (m1.col!=m2.row)
{
cout<<"两矩阵不能相乘!\n";
return t;
}
if (m*n>0)
{
int *s=new int[m*n];
for (i=0;i<m;i++)
for (j=0;j<n;j++)
{
*(s+i*n+j)=0;
for (k=0;k<m1.col;k++)
*(s+i*n+j)+=*(m1.p+i*m1.col+k)**(m2.p+k*n+j);
}
t.p=s;t.row=m;t.col=n;
return t;
}
return t;
}
void Matrix::transf()
{
if (p)
{
int i,j,temp,*t;
if (row==col)
{
for (i=0;i<row;i++)
for (j=0;j<=i;j++)
{
temp=*(p+i*col+j); //p[i][j]
*(p+i*col+j)=*(p+j*col+i);
*(p+j*col+i)=temp;
}
}
else
{
t=new int[row*col];
for(i=0;i<row;i++)
for (j=0;j<col;j++)
*(t+j*row+i)=*(p+i*col+j);
i=row;row=col;col=i;
delete []p;
p=t;
}
}
}
void main(void)
{
Matrix m1(2,3),m2(2,3),m3(3,3),m4;
cout<<"\n矩阵m1:\n";
m1.show();
cout<<"\n矩阵m2:\n";
m2.show();
cout<<"\n矩阵m3:\n";
m3.show();
m4=m3;
cout<<"\n执行m4=m3后,矩阵m4:\n";
m4.show();
m4=m1+m2;
cout<<"\n矩阵m4=m1+m2:\n";
m4.show();
m4=m1*m3;
cout<<"\n矩阵m4=m1*m3:\n";
m4.show();
m1.transf();
cout<<"\n转置后的矩阵m1:\n";
m1.show();
m3.transf();
cout<<"\n转置后的矩阵m3:\n";
m3.show();
}
急用!请大家帮帮忙啊!先谢了啊!