#pragma once
#include<iostream>
#include<iomanip>
#include<cstring>
using std::cout;
using std::endl;
using std::cin;
using std::setw;
using std::right;
using std::memset;
class Matrix {
protected:
int row, //行数
col, //列数
**arr; //矩阵数组指针
public:
//Constructor
Matrix(int row = 0, int col = 0) :row(row), col(col) {
init(row, col);
}
//Copy constructor
Matrix(const Matrix &m) :row(m.row), col(m.col) {
init(row, col);
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
arr[i][j] = m.arr[i][j];
}
//Destructor
~Matrix() {
del();
}
//构造矩阵
void init(int row, int col) {
if (row && col) {
arr = new int*[row];
for (int i = 0; i < row; i++) {
arr[i] = new int[col];
for (int j = 0; j < col; j++)
arr[i][j] = 0;
}
} else
cout << endl << "length cannot be zero." << endl;
}
//删除矩阵
void del() {
if (arr) {
for (int i = 0; i < row; i++)
if (arr[i]) {
delete[] arr[i];
arr[i] = nullptr;
}
if (arr)
delete[] arr;
arr = nullptr;
}
}
//输入
void input() {
cout << "waiting for input: (" << row << ", " << col << ")" << endl;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
cin >> arr[i][j];
}
//输出
void output() {
cout << "output: (" << row << ", " << col << ")" << endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
cout << setw(6) << right << arr[i][j];
cout << endl;
}
}
//int * Matrix
friend Matrix operator*(const int n, const Matrix &m) {
Matrix res(m);
for (int i = 0; i < res.row; i++)
for (int j = 0; j < res.col; j++)
res.arr[i][j] *= n;
return res;
}
//Matrix + Matrix
Matrix operator+(const Matrix &m) {
Matrix res(m.row, m.col);
if (row == m.row && col == m.col) {
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
res.arr[i][j] = arr[i][j] + m.arr[i][j];
} else
cout << endl << "Matrices don't match" << endl;
return res;
}
//Matrix * Matrix
Matrix operator*(const Matrix &m) {
Matrix res(row, m.col);
if (row != m.col)
cout << endl << "row has to equals col" << endl;
else
for (int i = 0; i < res.row; i++)
for (int j = 0; j < res.col; j++)
for (int k = 0; k < res.row; k++)
res.arr[i][j] += arr[i][k] * m.arr[k][j];
return res;
}
};