⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 116.cpp

📁 c++课程习题集的源代码
💻 CPP
字号:
#include<iostream.h>
 class matrix
{
 public:
   matrix(int r=2,int c=2);
   matrix(matrix &m);
   ~matrix();
   void set(void);
   matrix operator =(matrix &m);
   matrix operator +(matrix &m);//矩阵加法
   matrix operator -(matrix &m);//矩阵减法
   matrix operator *(matrix &m);//矩阵乘法
   double operator ()(int x,int y);
   matrix rev(void);
   friend ostream& operator <<(ostream& out,matrix &m); 
 private:
   int row;
   int col;
   double **p;
};
 matrix::matrix(int r,int c)
{
  int i;
  row=r;
  col=c;
  p=new double*[row];
  for(i=0;i<row;i++)
   *(p+i)=new double[col];
}
 matrix::matrix(matrix &m)
{
  int i,j;
  row=m.row;
  col=m.col;
  p=new double*[row];
  for(i=0;i<row;i++)
   *(p+i)=new double[col];
  for(i=0;i<row;i++)
   for(j=0;j<col;j++)
	*(*(p+i)+j)=*(*(m.p+i)+j);
}
 matrix::~matrix()
{
  int i;
  for(i=0;i<row;i++)
	delete []*(p+i);
  delete[]p;
}
 void matrix::set(void)
{
  int i,j;
  cout<<"请输入矩阵元素:"<<endl;
  for(i=0;i<row;i++)
   for(j=0;j<col;j++)
	cin>>*(*(p+i)+j);
}
 matrix matrix::operator =(matrix &m)
{
  int i,j;
  for(i=0;i<row;i++)
   for(j=0;j<col;j++)
	*(*(p+i)+j)=*(*(m.p+i)+j);
  return(*this);
}
 matrix matrix:: operator +(matrix &m)
{
  int i,j;
  matrix a(row,col);
  if(row!=m.row||col!=m.col)
   throw 0;
  for(i=0;i<row;i++)
   for(j=0;j<col;j++)
	*(*(a.p+i)+j)=*(*(p+i)+j)+*(*(m.p+i)+j);
  return(a); 
}
 matrix matrix::operator -(matrix &m)
{
  int i,j;
  matrix a(row,col);
  if(row!=m.row||col!=m.col)
   throw 0;
  for(i=0;i<row;i++)
   for(j=0;j<col;j++)
	*(*(a.p+i)+j)=*(*(p+i)+j)-*(*(m.p+i)+j);
  return(a); 
}
 matrix matrix::operator *(matrix &m)
{
  if(col!=m.row)//相乘时,矩阵尺寸不匹配
   throw 0;//抛出异常
  int i,j,k;
  double sum;
  matrix a(row,m.col);
  for(i=0;i<row;i++)
   for(j=0;j<m.col;j++)
   {
	for(k=0,sum=0;k<col;k++)
 	 sum=sum+*(*(p+i)+k)**(*(m.p+k)+j);
	 *(*(a.p+i)+j)=sum;
   }
  return(a); 
}
 double matrix::operator ()(int x,int y)
{
 if(x>row||y>col)//下标越界
  throw 0.0;//抛出异常
 return(*(*(p+x-1)+y-1));
}
 matrix matrix::rev(void)//矩阵转置
{
 int i,j;
 matrix a(col,row);
 for(i=0;i<row;i++)
  for(j=0;j<col;j++)
   *(*(a.p+j)+i)=*(*(p+i)+j);
 return(a); 
}
 ostream& operator <<(ostream& out,matrix &m)
{
 int i,j;
 for(i=0;i<m.row;i++)
 {
  for(j=0;j<m.col;j++)
   out<<*(*(m.p+i)+j)<<" ";
  out<<endl;
 }
 return(out);
}
 int main()
{
 matrix a(2,3),b(3,2);
 a.set();
 b=a.rev();
 cout<<"矩阵a:"<<endl;
 cout<<a;
 cout<<"矩阵a的转置b:"<<endl;
 cout<<b;
 return(0);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -