定义一个Matrix类,实现矩阵的加法和乘法
1 #include<iostream> 2 using namespace std; 3 4 class Matrix 5 { 6 int row;//矩阵的行 7 int col;//矩阵的列 8 int **a;//保存二维数组的元素 9 public: 10 Matrix();//默认构造函数 11 Matrix(int r, int c); 12 Matrix(const Matrix &is);//拷贝构造函数 13 void Set();//输入矩阵元素 14 void Madd(const Matrix &is);//矩阵加 15 Matrix Mmul(const Matrix &is);//矩阵乘 16 void display();//显示矩阵元素 17 }; 18 19 Matrix::Matrix(int r, int c) 20 { 21 row = r; 22 col = c; 23 a = (int **)malloc(sizeof(int*)*row); 24 for (int r = 0; r < row; r++) 25 { 26 *(a + r) = (int*)malloc(sizeof(int)*col); 27 } 28 } 29 30 Matrix::Matrix(const Matrix & is) 31 {//拷贝构造函数 32 row = is.row; 33 col = is.col; 34 a = new int*[row]; 35 for (int i = 0; i < row; i++) 36 { 37 a[i] = new int[col]; 38 } 39 a = is.a; 40 } 41 42 void Matrix::Set() 43 { 44 printf("请输入数:\n"); 45 for (int i = 0; i < row; i++) 46 for (int j = 0; j < col; j++) 47 cin >> a[i][j]; 48 } 49 50 void Matrix::Madd(const Matrix & is) 51 { 52 if (row != is.row || col != is.col)//判断两矩阵是否符合相加条件 53 { 54 cout << "相加的矩阵必须行和列一致"; 55 } 56 else 57 { 58 for (int i = 0; i < row; i++) 59 { 60 for (int j = 0; j < col; j++) 61 { 62 a[i][j] += is.a[i][j]; 63 } 64 } 65 } 66 } 67 68 Matrix Matrix::Mmul(const Matrix & is) 69 { 70 Matrix M3(this->row, is.col); 71 if (this->col != is.row)//判断是否符合相乘条件 72 { 73 cout << "不符合两矩阵相乘的条件"; 74 } 75 else 76 { 77 for (int i = 0; i < M3.row; i++) 78 { 79 for (int j = 0; j < M3.col; j++) 80 { 81 M3.a[i][j] = 0; 82 for (int n = 0; n < is.row; n++) 83 { 84 M3.a[i][j] += this->a[i][n] * is.a[n][j]; 85 } 86 } 87 } 88 } 89 return M3; 90 } 91 92 void Matrix::display() 93 {//输出矩阵 94 for (int i = 0; i < row; i++) 95 { 96 for (int j = 0; j < col; j++) 97 { 98 cout << a[i][j] << " "; 99 } 100 cout << endl; 101 } 102 cout << endl; 103 } 104 105 int main() 106 { 107 Matrix m1(3, 3); 108 m1.Set(); 109 m1.display(); 110 Matrix m2(3, 3); 111 m2.Set(); 112 m2.display(); 113 Matrix m3(3, 2); 114 m3.Set(); 115 m3.display(); 116 cout << "m1+m2=" << endl; 117 m1.Madd(m2); 118 m1.display(); 119 Matrix m4(m1.Mmul(m3)); 120 cout << "m1*m3=" << endl; 121 m4.display(); 122 system("pause"); 123 return 0; 124 }
运行结果: