#define MATRIX_H
#include<iostream>
using namespace std;
template <typename T>
class Matrix{
template <typename T>
friend ostream & operator<<(ostream & os,const Matrix<T> & ma);
template <typename T>
friend istream & operator>>(istream & is,Matrix<T> & ma);
public:
Matrix(int x=0,int y=0);
Matrix(const Matrix & mt);
~Matrix();
friend Matrix<T> operator + (Matrix<T> & mt1,Matrix<T> & mt2);
friend Matrix<T> & operator += (Matrix<T> & mt1,Matrix<T> & mt2);
Matrix operator = ( Matrix<T> & mt);
/*
operator+
operator+=
operator=
*/
private:
int m,n;
T * * ptr;
};
template <typename 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];
if(ptr==NULL){
cout<<"内存空间不足!"<<endl;
exit(-1);
}
}
template <typename T>
Matrix<T>::Matrix(const Matrix & mt){
m=mt.m;
n=mt.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]=mt.ptr[i][j];
}
template <typename T>
Matrix<T>::~Matrix(){
for(int i=0;i<m;i++)
delete [] ptr[i];
delete [] ptr;
}
template <typename T>
ostream & operator<<(ostream & os,const Matrix<T> & ma){
for(int i=0;i<ma.m;i++){
for(int j=0;j<ma.n;j++)
os<<ma.ptr[i][j]<<"\t";
os<<endl;
}
return os;
}
template <typename T>
istream & operator>>(istream & is,Matrix<T> & ma){
for(int i=0;i<ma.m;i++){
cout<<"请输入第"<<i+1<<"行"<<ma.n<<"元素:";
for(int j=0;j<ma.n;j++)
is>>ma.ptr[i][j];
}
return is;
}
template <typename T>
Matrix<T> operator + (Matrix<T> & mt1,Matrix<T> & mt2)
{
Matrix tmp[i][j];
for(int i=0;i<mt.m;i++)
for(int j=0;j<mt.n;j++)
tmp[i][j]=mt1.ptr[i][j]+mt2.ptr[i][j];
return tmp[i][j];
}
template <typename T>
Matrix<T> & operator += (Matrix<T> & mt1,Matrix<T> & mt2)
{
for(int i=0;i<mt.m;i++)
for(int j=0;j<mt.n;j++)
mt1.ptr[i][j]+=mt2.ptr[i][j];
return mt1.ptr[i][j];
}
template <typename T>
Matrix<T> Matrix<T>::operator = ( Matrix<T> & mt)
{
m=mt.m;
n=mt.n;
for(int i=0;i<mt.m;i++)
for(int j=0;j<mt.n;j++)
ptr[i][j]=mt.ptr[i][j];
return *this;
}
一只萌萌小番薯
精慕HU
随时随地看视频慕课网APP
相关分类