#ifndef _MATRIX_H_
#define _MATRIX_H_
#include <iostream>
using namespace std;
template<class ElemType>
class Matrix
{
protected:
ElemType *elems;
int rows,cols;
public:
Matrix(int rs,int cs);
void SetMatrix(const int a[]);
void GetMatrix()const;
virtual ~Matrix();
int GetRows()const;
int GetCols()const;
ElemType &operator()(int i,int j);
Matrix(const Matrix<ElemType> ©);
Matrix<ElemType> &operator=(const Matrix<ElemType> ©);
};
template<class ElemType>
void Matrix<ElemType>::GetMatrix()const
{
for(int i=0;i<rows*cols;i++)
cout<<elems[i]<<endl;
}
template<class ElemType>
void Matrix<ElemType>::SetMatrix(const int a[])
{
for(int i=0;i<rows*cols;i++)
elems[i]=a[i];
}
template<class ElemType>
Matrix<ElemType>::Matrix(int rs,int cs)
{
if(rs<1||cs<1)
cout<<"行数或列数无效"<<endl;
rows=rs;
cols=cs;
elems=new ElemType[rows*cols];
}
template<class ElemType>
ElemType &Matrix<ElemType>::operator ()(int i,int j)
{
if(i<1||i>rows||j<1||j>cols)
cout<<"下标出界"<<endl;
return elems[(i-1)*cols+j-1];
}
template<class ElemType>
Matrix<ElemType>::~Matrix()
{
delete []elems;
}
template<class ElemType>
int Matrix<ElemType>::GetRows()const
{
return rows;
}
template<class ElemType>
int Matrix<ElemType>::GetCols()const
{
return cols;
}
template<class ElemType>
Matrix<ElemType>::Matrix(const Matrix<ElemType> ©)
{
cols=copy.GetCols();
rows=copy.GetCols();
elems=null;
elems=new Elem[cols*rows];
}
template<class ElemType>
Matrix<ElemType>& Matrix<ElemType>::operator=(const Matrix<ElemType>& copy)
{
if(this!=©)
{
cols=copy.GetCols();
rows=copy.GetCols();
elems=null;
elems=new Elem[cols*rows];
}
return *this;
}
#endif
#include "Matrix.h"
#include <iostream>
using namespace std;
void main()
{
Matrix<int> a(3,3);
int c[9];
for(int i=0;i<9;i++)
{
c[i]=i;
}
a.SetMatrix(c);
a.GetMatrix();
cout<<a(2,1)<<endl;
}