实验——矩阵运算(1)
创建m行n列矩阵,实现赋值、插入、提取、加法运算符重载。整型与单位阵转换。
matrix.h
1 #include<iostream> 2 using namespace std; 3 4 class Square_matrix{//m行n列 5 public: 6 Square_matrix(int inputm,int inputn) 7 { 8 m=inputm; 9 n=inputn; 10 p=new int*[m]; 11 int i,j; 12 for(i=0;i<m;i++) 13 p[i]=new int[n]; 14 cout<<"define a ( "<<m<<","<<n<<" )matrix."<<endl; 15 } 16 Square_matrix(int inputn) 17 { 18 n=inputn; 19 m=inputn; 20 int i,j; 21 p=new int*[m]; 22 for(i=0;i<m;i++) 23 p[i]=new int[n]; 24 for(i=0;i<m;i++) 25 { 26 for(j=0;j<n;j++) 27 { 28 if(i==j) 29 p[i][j]=1; 30 else 31 p[i][j]=0; 32 } 33 } 34 cout<<"define a ("<<n<<") identity matrix."<<endl; 35 } 36 Square_matrix(const Square_matrix &m0) 37 { 38 n=m0.n; 39 m=m0.m; 40 int i,j; 41 for(i=0;i<m;i++) 42 for(j=0;j<n;j++) 43 p[i][j]=m0.p[i][j]; 44 } 45 friend ostream &operator<<(ostream &,const Square_matrix &); 46 friend istream &operator>>(istream &,Square_matrix &); 47 Square_matrix & operator=(const Square_matrix & m) 48 { 49 if(this==&m) return *this; 50 if(n!=m.n) cout<<"only homography matrix can be added."<<endl; 51 else 52 { 53 int i,j; 54 delete p; 55 for(i=0;i<n;i++) 56 p[i]=new int[m.n]; 57 n=m.n; 58 for(i=0;i<n;i++) 59 for(j=0;j<n;j++) 60 p[i][j]=m.p[i][j]; 61 } 62 return *this; 63 } 64 Square_matrix operator+(const Square_matrix &m0) 65 { 66 if(n!=m0.n||m!=m0.m) 67 { 68 cout<<"only homography matrix can be added."<<endl; 69 return *this; 70 } 71 else{ 72 Square_matrix mt(m,n); 73 int i,j; 74 for(i=0;i<m;i++) 75 for(j=0;j<n;j++) 76 mt.p[i][j]=p[i][j]+m0.p[i][j]; 77 return mt; 78 } 79 }; 80 ~Square_matrix() 81 { 82 int i,j; 83 for(i=0;i<n;i++) 84 delete []p[i]; 85 delete []p; 86 cout<<"the matrix is deleted!"<<endl; 87 } 88 private: 89 int **p; 90 int m; 91 int n; 92 }; 93 94 istream &operator>> (istream & input,Square_matrix &m) 95 { 96 int i,j; 97 int mn=m.n; 98 cout<<"Input the elements according to the row:"<<endl; 99 for(i=0;i<mn;i++) 100 { 101 for(j=0;j<mn;j++) 102 { 103 input>>m.p[i][j]; 104 } 105 } 106 return input; 107 } 108 109 ostream &operator<< (ostream & output,const Square_matrix &m) 110 { 111 int i,j; 112 int mn=m.n; 113 for(i=0;i<mn;i++) 114 { 115 for(j=0;j<mn;j++) 116 output<<m.p[i][j]<<" "; 117 output<<endl; 118 } 119 return output; 120 }
main.cpp
1 #include<iostream> 2 #include "matrix.h" 3 4 using namespace std; 5 6 int main() 7 { 8 // const int n=2; 9 int n; 10 cout<<"the order of the Square Matrix:"; 11 cin>>n; 12 Square_matrix m0(n,n); 13 cout<<"Input the elements:"<<endl; 14 cin>>m0; 15 cout<<"m0:"<<endl; 16 cout<<m0; 17 Square_matrix m1(n,n); 18 cout<<"m1=m0"<<endl<<"m1:"<<endl; 19 m1=m0; 20 cout<<m1; 21 Square_matrix m2(n,n); 22 m2=m0+Square_matrix(n); 23 cout<<"m2=m0+Intmatrix("<<n<<")"<<endl<<"m2:"<<endl; 24 cout<<m2; 25 return 0; 26 }
运行结果:



浙公网安备 33010602011771号