矩阵

#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> &copy);
		Matrix<ElemType> &operator=(const Matrix<ElemType> &copy);
};

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> &copy)
{
	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!=&copy)
	{
		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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值