重載*運算符為友元函數。
1 #include <iostream> 2 #include <cmath> 3 using namespace std; 4 5 class Matrix{ 6 public: 7 Matrix(){} 8 Matrix(int,int); 9 void setMatrix(); 10 void showMatrix(); 11 void showTransposedMatrix(); 12 friend Matrix operator *(Matrix m1,Matrix m2); 13 protected: 14 int m; 15 int n; 16 int mn; 17 double* matrixPtr; 18 double* transposedMPtr; 19 void transpose(); 20 }; 21 22 class SquareMatrix:public Matrix{ 23 public: 24 SquareMatrix(){} 25 SquareMatrix(int); 26 void setSquareMatrix(); 27 void setDet(); 28 void getDet(); 29 private: 30 double det; 31 }; 32 33 Matrix::Matrix(int mt,int nt){ 34 m=mt; 35 n=nt; 36 mn=m*n; 37 matrixPtr=new double[mn]; 38 } 39 40 void Matrix::setMatrix(){ 41 cout<<"輸入矩陣的行數和列數:"<<endl; 42 cin>>m>>n; 43 mn=m*n; 44 matrixPtr=new double[mn]; 45 for(int i=0;i<mn;i++) 46 cin>>matrixPtr[i]; 47 } 48 49 void Matrix::transpose(){ 50 transposedMPtr=new double[mn]; 51 for(int i=0;i<n;i++) 52 for(int j=0;j<m;j++) 53 transposedMPtr[m*i+j]=matrixPtr[n*j+i]; 54 } 55 56 void Matrix::showMatrix(){ 57 for(int i=0;i<m;i++){ 58 for(int j=0;j<n;j++) 59 cout<<matrixPtr[n*i+j]<<' '; 60 cout<<endl; 61 } 62 } 63 64 void Matrix::showTransposedMatrix(){ 65 for(int i=0;i<n;i++){ 66 for(int j=0;j<m;j++) 67 cout<<transposedMPtr[m*i+j]<<' '; 68 cout<<endl; 69 } 70 } 71 72 Matrix operator *(Matrix m1,Matrix m2){ 73 Matrix m3(m1.m,m2.n); 74 for(int i=0;i<m3.m;i++) 75 for(int j=0;j<m3.n;j++){ 76 double val=0; 77 for(int k=0;k<m2.m;k++) 78 val+=m1.matrixPtr[m1.n*i+k]*m2.matrixPtr[m2.n*k+j]; 79 m3.matrixPtr[m3.n*i+j]=val; 80 } 81 return m3; 82 } 83 84 SquareMatrix::SquareMatrix(int m){ 85 Matrix(m,m); //right? 86 } 87 88 void SquareMatrix::setSquareMatrix(){ 89 cout<<"輸入方陣的階數:"<<endl; 90 cin>>m; 91 n=m; 92 mn=m*n; 93 matrixPtr=new double[mn]; 94 for(int i=0;i<mn;i++) 95 cin>>matrixPtr[i]; 96 } 97 98 void SquareMatrix::setDet(){ 99 double valDet(double*,int); 100 det=valDet(matrixPtr,m); 101 } 102 103 void SquareMatrix::getDet(){ 104 cout<<det<<endl; 105 } 106 double valDet( double *detPtr, int rank) 107 { 108 double val=0; 109 if(rank==1) return detPtr[0]; 110 for(int i=0;i<rank;i++) //計算余子式保存在nextDetPtr[]中 111 { 112 double *nextDetPtr=new double[(rank-1)*(rank-1)]; 113 for(int j=0;j<rank-1;j++) 114 for(int k=0;k<i;k++) 115 nextDetPtr[j*(rank-1)+k]=detPtr[(j+1)*rank+k]; 116 for(int j=0;j<rank-1;j++) 117 for(int k=i;k<rank-1;k++) 118 nextDetPtr[j*(rank-1)+k]=detPtr[(j+1)*rank+k+1]; 119 val+=detPtr[i]*valDet(nextDetPtr,rank-1)*pow(-1.0,i); 120 } 121 return val; 122 } 123 124 int main(){ 125 Matrix m1,m2,m3; 126 m1.setMatrix(); 127 m2.setMatrix(); 128 m3=m1*m2; 129 m3.showMatrix(); 130 return 0; 131 }