#include <iostream>
#include <iomanip>
using namespace std;
class Matrix {
private:
int row;
int column;
int **mat = nullptr;
public:
Matrix(int r = 1,int c = 1):row(r),column(c) {
mat = new int*[row];
for (int i = 0; i < row; i++)
mat[i] = new int[column];
}
Matrix(const Matrix &m):row(m.row),column(m.column) {
mat = new int*[row];
for (int i = 0; i < row; i++) {
mat[i] = new int[column];
for (int j = 0; j < column; j++)
mat[i][j] = m.mat[i][j];
}
}
~Matrix() {
for (int i = 0; i < row; i++)
delete [] mat[i];
delete [] mat;
}
void input() {
for (int i = 0; i < row; i++)
for (int j = 0; j < column; j++)
cin >> mat[i][j];
}
void display() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++)
cout << setw(10) << mat[i][j];
cout << endl;
}
}
Matrix operator*(const Matrix &m) {
if (column == 1 && row == 1) {
Matrix temp(m.row,m.column)
for (int i = 0; i < m.row; i++)
for (int j = 0; j < m.column; j++)
temp.mat[i][j] = mat[0][0] * m.mat[i][j];
return temp;
}
if (m.column == 1 && m.row == 1) {
Matrix temp(row,column)
for (int i = 0; i < row; i++)
for (int j = 0; j < column; j++)
temp.mat[i][j] = mat[i][j] * m.mat[0][0];
return temp;
}
Matrix temp(row,m.column);
for (int i = 0; i < row; i++)
for (int j = 0; j < m.column; j++) {
temp.mat[i][j] = 0;
for (int k = 0; k < column; k++)
temp.mat[i][j] += mat[i][k] * m.mat[k][j];
}
return temp;
}
};
int main () {
int r1,c1,r2,c2;
cin >> r1 >> c1;
Matrix m1(r1,c1);
m1.input();
cin >> r2 >> c2;
Matrix m2(r2,c2);
m2.input();
if (c1 == r2 || (c1 == 0 && r2 == 0)) {
Matrix m3 = m1 * m2;
m3.display();
}
cout << "Invalid Matrix multiplication!" << endl;
return 0;
return 0;
}
标签:Matrix,mat,int,编程,++,C语言,column,打卡,row
From: https://www.cnblogs.com/sugar-refinery/p/17406475.html