Defines a Matrix class to implement addition and multiplication of matrices.
# Include <iostream> using namespace std; class Matrix {int row; // int col of the Matrix row; // int of the Matrix column **; // Save the public: Matrix (); // default constructor Matrix (int r, int c); Matrix (const Matrix & is ); // copy the constructor void Madd (const Matrix & is); // The Matrix is added with Matrix Mmul (const Matrix & is); // The Matrix is multiplied by void display (); // display Matrix element}; Matrix: Matrix (int r, int c) {row = r; col = c; a = (int **) malloc (sizeof (int *) * row); for (int r = 0; r <row; r ++) {* (a + R) = (int *) malloc (sizeof (int) * col);} printf ("Please input number: \ n"); for (int I = 0; I <row; I ++) for (int j = 0; j <col; j ++) cin> a [I] [j];} Matrix :: matrix (const Matrix & is) {// copy the constructor row = is. row; col = is. col; a = new int * [row]; for (int I = 0; I <row; I ++) {a [I] = new int [col];} a = is. a;} void Matrix: Madd (const Matrix & is) {if (row! = Is. row | col! = Is. col) // determine whether the two matrices meet the addition condition {cout <"the added matrix must have the same rows and columns";} else {for (int I = 0; I <row; I ++) {for (int j = 0; j <col; j ++) {a [I] [j] + = is. a [I] [j] ;}}} Matrix: Mmul (const Matrix & is) {Matrix M3 (this-> row, is. col); if (this-> col! = Is. row) // determine whether the multiplication condition {cout <"does not match the condition of two matrices multiplication";} else {for (int I = 0; I <M3.row; I ++) {for (int j = 0; j <M3.col; j ++) {M3.a [I] [j] = 0; for (int n = 0; n <is. row; n ++) {M3.a [I] [j] + = this-> a [I] [n] * is. a [n] [j] ;}}} return M3;} void Matrix: display () {// output Matrix for (int I = 0; I <row; I ++) {for (int j = 0; j <col; j ++) {cout <a [I] [j] <"";} cout <endl ;}cout <endl ;}int main () {Matrix m1 (3, 3); m1.display (); Matrix m2 (3, 3 ); m2.display (); Matrix m3 (3, 2); m3.display (); cout <"m1 + m2 =" <endl; m1.Madd (m2); m1.display (); matrix m4 (m1.Mmul (m3); cout <"m1 * m3 =" <endl; m4.display (); system ("pause"); return 0 ;}
Running result: