⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 matrix.cpp

📁 VC矩阵类的编写
💻 CPP
字号:
#include<iostream.h>class matrix{	short rows,cols;	double * elems;public:	matrix(short rows,short cols);	~matrix();	double operator () (short row,short col);	void setelem(short row,short col,double val);	friend matrix operator + (matrix p,matrix q);	friend matrix operator - (matrix p,matrix q);	friend matrix operator * (matrix p,matrix q);	void print();};matrix::matrix(short rows,short cols){	matrix::rows=rows;	matrix::cols=cols;    elems=new double[rows * cols];}inline matrix::~matrix(){//	delete []elems;}double matrix::operator () (short row,short col){	return (row>=1 && row<=rows && col>=1 && col<=cols) ? elems[(row-1)*cols+(col-1)] : 0.0;}void matrix::setelem(short row,short col,double val){	if(row>=1 && row<=rows && col>=1 && col<=cols)		elems[(row-1)*cols+(col-1)]=val;}matrix operator + (matrix p,matrix q){	matrix m(p.rows,p.cols);	if(p.rows!=q.rows || p.cols!=q.cols)		return m;	for(int r=1;r<=p.rows;r++)		for(int c=1;c<=p.cols;c++)			m.setelem(r,c,p(r,c)+q(r,c));		return m;}matrix operator - (matrix p,matrix q){	matrix m(p.rows,p.cols);	if(p.rows!=q.rows || p.cols!=q.cols)		return m;	for(int r=1;r<=p.rows;r++)		for(int c=1;c<=p.cols;c++)			m.setelem(r,c,p(r,c)-q(r,c));		return m;}matrix operator * (matrix p,matrix q){	matrix m(p.rows,q.cols);    if(p.cols!=q.rows)		return m;	for(int r=1;r<=p.rows;r++)		for(int c=1;c<=q.cols;c++)		{			m.setelem(r,c,0.0);			for(int i=1;i<=p.cols;i++)				m.setelem(r,c,m(r,c)+p(r,i)*q(i,c));		}	return m;}void matrix::print(){	for(int r=1;r<=this->rows;++r)	{		for(int c=1;c<=this->cols;c++)		cout<<(*this)(r,c)<<" ";		cout<<endl;	}}main(){	matrix a(2,3),b(2,3),c(3,2),d(2,3),e(2,2);	a.setelem(1,1,1.0);    a.setelem(1,2,2.0);    a.setelem(1,3,3.0);	a.setelem(2,1,4.0);	a.setelem(2,2,5.0);	a.setelem(2,3,6.0);	b.setelem(1,1,1.0);	b.setelem(1,2,2.0);	b.setelem(1,3,3.0);	b.setelem(2,1,4.0);	b.setelem(2,2,5.0);	b.setelem(2,3,6.0);	c.setelem(1,1,1.0);	c.setelem(1,2,4.0);	c.setelem(2,1,2.0);	c.setelem(2,2,5.0);	c.setelem(3,1,3.0);	c.setelem(3,2,6.0);	a.print();	b.print();	c.print();	d=a + b;	d.print();	d=a - b;	d.print();   	e=a * c;	e.print();   	return 1;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -