矩阵类实现
实现 Matrix,+,-,*,clear()方法
代码
#include<iostream>
#include<stdlib.h>
#include<memory.h>
using namespace std;
const int MAXN=1010;
const int MAXM=1010;
struct Matrix{
int n,m;
int a[MAXN][MAXM];
void clear()
{
n=m=0;
memset(a,0,sizeof(a));
}
Matrix operator+(const Matrix *b)const
{
Matrix tmp;
tmp.n=n;tmp.m=m;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
tmp.a[i][j]=a[i][j]+b->a[i][j];
}
}
return tmp;
}
Matrix operator-(const Matrix *b)const{
Matrix tmp;
tmp.n=n;tmp.m=m;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
tmp.a[n][m]=a[n][m]-b->a[i][j];
}
}
return tmp;
}
Matrix operator*(const Matrix *b)const{
Matrix tmp;
tmp.clear();
tmp.n=n;tmp.m=m;
for(int i=0;i<n;i++)
{
for(int j=0;j<b->m;j++)
{
for(int k=0;k<m;k++)
{
tmp.a[i][j]=a[i][k]*b->a[k][j];
}
}
}
return tmp;
}
};
int main()
{
Matrix* a;
a=(Matrix*)malloc(sizeof(struct Matrix));
a->clear();
a->n=3,a->m=3;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
a->a[i][j]=i*3+j;
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cout<<a->a[i][j];
}
cout<<endl;
}
return 0;
}