The overloaded * operator is a friend function.
1#include <iostream>2#include <cmath>3 using namespacestd;4 5 classmatrix{6 Public:7 Matrix () {}8Matrix (int,int);9 voidSetMatrix ();Ten voidShowmatrix (); One voidShowtransposedmatrix (); AFriend Matrixoperator*(Matrix m1,matrix m2); - protected: - intm; the intN; - intmn; - Double*matrixptr; - Double*transposedmptr; + voidtranspose (); - }; + A classSquarematrix: Publicmatrix{ at Public: - Squarematrix () {} -Squarematrix (int); - voidSetsquarematrix (); - voidSetdet (); - voidGetdet (); in Private: - Doubledet; to }; + -Matrix::matrix (intOtnintNT) { them=MT; *n=NT; $mn=m*N;Panax NotoginsengMatrixptr=New Double[MN]; - } the + voidMatrix::setmatrix () { Acout<<"Enter the number of rows and columns of the matrix:"<<Endl; theCin>>m>>N; +mn=m*N; -Matrixptr=New Double[MN]; $ for(intI=0; i<mn;i++) $Cin>>Matrixptr[i]; - } - the voidMatrix::transpose () { -Transposedmptr=New Double[MN];Wuyi for(intI=0; i<n;i++) the for(intj=0; j<m;j++) -transposedmptr[m*i+j]=matrixptr[n*j+i]; Wu } - About voidMatrix::showmatrix () { $ for(intI=0; i<m;i++){ - for(intj=0; j<n;j++) -cout<<matrixptr[n*i+j]<<' '; -cout<<Endl; A } + } the - voidMatrix::showtransposedmatrix () { $ for(intI=0; i<n;i++){ the for(intj=0; j<m;j++) thecout<<transposedmptr[m*i+j]<<' '; thecout<<Endl; the } - } in theMatrixoperator*(Matrix m1,matrix m2) { the Matrix m3 (M1.M,M2.N); About for(intI=0; i<m3.m;i++) the for(intj=0; j<m3.n;j++){ the DoubleVal=0; the for(intk=0; k<m2.m;k++) +val+=m1.matrixptr[m1.n*i+k]*m2.matrixptr[m2.n*k+j]; -m3.matrixptr[m3.n*i+j]=Val; the }Bayi returnm3; the } the -Squarematrix::squarematrix (intm) { -Matrix (M,M);//Right ? the } the the voidSquarematrix::setsquarematrix () { thecout<<"Enter the order of the square:"<<Endl; -Cin>>m; then=m; themn=m*N; theMatrixptr=New Double[MN];94 for(intI=0; i<mn;i++) theCin>>Matrixptr[i]; the } the 98 voidSquarematrix::setdet () { About DoubleValdet (Double*,int); -det=Valdet (matrixptr,m);101 }102 103 voidSquarematrix::getdet () {104cout<<det<<Endl; the }106 DoubleValdet (Double*detptr,intrank)107 {108 DoubleVal=0;109 if(rank==1)returndetptr[0]; the for(intI=0; i<rank;i++)//calculation cofactor saved in nextdetptr[]111 { the Double*nextdetptr=New Double[(rank-1) * (rank-1)];113 for(intj=0; j<rank-1; j + +) the for(intk=0; k<i;k++) thenextdetptr[j* (rank-1) +k]=detptr[(j+1) *rank+K]; the for(intj=0; j<rank-1; j + +)117 for(intk=i;k<rank-1; k++)118nextdetptr[j* (rank-1) +k]=detptr[(j+1) *rank+k+1];119Val+=detptr[i]*valdet (nextdetptr,rank-1) *pow (-1.0, i); - }121 returnVal;122 }123 124 intMain () { the Matrix m1,m2,m3;126 M1.setmatrix ();127 M2.setmatrix (); -M3=m1*m2;129 M3.showmatrix (); the return 0;131}
C + + implements matrix multiplication