#ifndef GUARD_MATRIX_H
#define GUARD_MATRIX_H
#include<iostream>
#include<iomanip>
using namespace std;
template<class T=double>
class matrix{
template<typename T>
friend ostream& operator<<(ostream&,const matrix<T>&);
public:
matrix(int x=0,int y=0);
matrix(const matrix& mx);
~matrix(){
free();
}
void setvalue(int r,int c,T x);
matrix<T> operator+(const matrix<T>&mx) const;
matrix<T> operator*(const matrix<T>&mx) const;
matrix<T>& operator=(const matrix<T>&mx);
private:
T **ptr;
int m,n;
void free();
};
template<class T>
matrix<T>::matrix(int x,int y){
m=x;
n=y;
ptr=new T*[m];
for(int i=0;i<m;i++)
ptr[i]=new T[n];
}
template<class T>
matrix<T>::matrix(const matrix<T> &mx){
m=mx.m;
n=mx.n;
ptr=new T*[m];
for(int i=0;i<m;i++)
ptr[i]=new T[n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
ptr[i][i]=mx.ptr[i][j];
}
template<class T>
void matrix<T>::setvalue(int r, int c, T x){
ptr[r][c]=x;
}
template<class T>
matrix<T>& matrix<T>::operator =(const matrix<T> &mx){
free();
m=mx.m;
n=mx.n;
ptr=new T*[m];
for(int i=0;i<m,i++)
ptr[i]=new T[n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
ptr[i][j]=mx.ptr[i][j];
return *this;
}
template<class T>
matrix<T> matrix<T>::operator +(const matrix<T> &mx) const{
if(m!=mx.m||n!=mx.n)
{
cout<<"they can not plus"<<endl;
return NULL;
}
matrix<T> temp(m,n);
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
temp.ptr[i][j]=ptr[i][j]+mx.ptr[i][j];
return temp;
}
template<class T>
void matrix<T>::free(){
for(int i=0;i<m;i++)
delete []ptr[i];
delete []ptr;
m=0;
n=0;
}
template<class T>
matrix<T> matrix<T>::operator *(const matrix<T> &mx) const{
if(this->n != mx.m)
{
cout<<"the two matrix can not multify"<<endl;
return NULL;
}
matrix temp(m,mx.n);
for(int i=0;i<m;i++)
for(int j=0;j<mx.n;j++){
T sum=NULL;
for(int k=0;k<n;k++)
sum+=ptr[i][k]*mx.ptr[k][j];
temp.ptr[i][j]=sum;
}
return temp;
}
template<class T>
ostream& operator<<(ostream& os, const matrix<T> &mx){
for(int i=0;i<mx.m;i++){
for(int j=0;j<mx.n;j++)
os<<setw(6)<<mx.ptr[i][j];
os<<endl;
}
return os;
}
#endif
实现矩阵类
最新推荐文章于 2022-03-19 09:38:33 发布