利用C++实现矩阵的构造,通过运算符的重载实现矩阵的乘法、加法等。并且实现矩阵形状的打印,矩阵的打印。
#include<iostream>
#include<memory>
#include<assert.h>
#include<stdlib.h>
using namespace std;
class Matrix{
public:
Matrix(int row, int col);
Matrix(int row, int col, int num);
~Matrix();
Matrix(const Matrix & other);
Matrix operator*(const Matrix& other);
Matrix operator+(const Matrix& other);
Matrix operator-(const Matrix& other);
int **a = nullptr;
int row, col;
void shape();
void Ma_pri();
};
int main(){
Matrix a(2,1);
Matrix b(1,2);
a.a[0][0] = 4;
a.a[1][0] = 2;
b.a[0][0] = 3;
b.a[0][1] = 5;
a.shape();
b.shape();
Matrix c = a*b;
c.shape();
c.Ma_pri();
Matrix d(3,3,1);
d.Ma_pri();
system("pause");
return 0;
}
Matrix::Matrix(int row, int col){
this->row = row;
this->col = col;
this->a = new int*[row];
for(int i=0;i<this->row;i++){
a[i] = new int[this->col];
}
}
Matrix::Matrix(int row, int col, int num){
this->row = row;
this->col = col;
this->a = new int*[row];
for(int i=0;i<this->row;i++){
a[i] = new int[this->col];
}
for(int i = 0; i < this->row; i++){
for(int j =0; j <this->row; j++){
this->a[i][j] = num;
}
}
}
Matrix::~Matrix(){
for(int i=0;i<this->row;i++){
if(a[i] != nullptr){
delete[] a[i];
a[i] = nullptr;
}
}
if(a != nullptr){
delete[] a;
a = nullptr;
}
}
Matrix::Matrix(const Matrix& other){
row = other.row;
col = other.col;
a = new int*[row];
for(int i=0;i<row;i++){
a[i] = new int[col];
memcpy(a[i], other.a[i],sizeof(int)*col);
}
}
Matrix Matrix::operator*(const Matrix& other){
if(this->col != other.row){
cout<<"shape error"<<endl;
exit(0);
}
Matrix m(this->row,other.col);
for(int i=0; i<this->row; i++){
for(int j=0;j<other.col;j++){
int sum = 0;
for(int k=0;k<this->col;k++){
sum += this->a[i][k] * other.a[k][j];
}
m.a[i][j] = sum;
}
}
return m;
}
Matrix Matrix::operator+(const Matrix& other){
if(this->col != other.col or this->row != other.row){
cout<<"shape error"<<endl;
exit(0);
}
Matrix m(this->row,this->col);
for(int i = 0;i < this->row; i++){
for(int j = 0; j < this-> col; j++){
m.a[i][j] = this->a[i][j] + other.a[i][j];
}
}
return m;
}
Matrix Matrix::operator-(const Matrix& other){
if(this->col != other.col or this->row != other.row){
cout<<"shape error"<<endl;
exit(0);
}
Matrix m(this->row,this->col);
for(int i = 0;i < this->row; i++){
for(int j = 0; j < this-> col; j++){
m.a[i][j] = this->a[i][j] - other.a[i][j];
}
}
return m;
}
void Matrix::shape(){
cout<<"("<<this->row<<","<<this->col<<")"<<endl;
}
void Matrix::Ma_pri(){
for(int i = 0; i < this->row; i++){
for(int j =0; j <this->row; j++){
cout<<this->a[i][j]<<" ";
}
cout<<endl;
}
}
|