10_84.cpp
上传用户:zipjojo
上传日期:2009-07-20
资源大小:70k
文件大小:3k
- #include<iostream.h>
- #include<iomanip.h>
- class matrix
- { //定义矩阵类
- short rows,cols; //矩阵的行、列
- double *elems; //存放矩阵中各元素,按行存放
- public:
- matrix(){}
- matrix(short r,short c);
- double operator ()(short r,short c);
- //重载运算符"()",用来返回元素值
- void setelem(short r,short c,double v);
- //给元素赋值
- 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 r,short c)
- {
- rows=r;
- cols=c;
- elems=new double[r*c];
- }
- double matrix::operator()(short r,short c)
- {
- return (r>=1 && r<=rows && c>=1 && c<=cols)?
- elems[(r-1)*cols+(c-1)]:0.0;
- }
- void matrix::setelem(short r,short c,double v)
- {
- if(r>=1 && r<=rows && c>=1 && c<=cols)
- elems[(r-1)*cols+(c-1)]=v;
- //在内存中是按照行顺序存放矩阵元素的,所以应对行、列进行换算,
- //算出在elems中的下标
- }
- 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<=rows;r++)
- {
- for(int c=1;c<=cols;c++)
- cout<<setw(7)<<(*this)(r,c);
- //注意:this指针的用法,此句只能写成(*this)(r,c)形式,其它形式错误
- //使用*this标识被该重载函数成员正在操作的对象
- cout<<endl;
- }
- }
- void main()
- {
- matrix a(2,3),b(2,3),c(3,2),d(2,3),e(2,2);
- a.setelem(1,1,-1.1);
- a.setelem(1,2,2.2);
- a.setelem(1,3,-3.3);
- a.setelem(2,1,4.4);
- a.setelem(2,2,-5.5);
- a.setelem(2,3,6.6);
- b.setelem(1,1,-1.2);
- b.setelem(1,2,2.3);
- b.setelem(1,3,-3.4);
- b.setelem(2,1,4.5);
- b.setelem(2,2,-5.6);
- b.setelem(2,3,6.7);
- c.setelem(1,1,-1.8);
- c.setelem(1,2,4.9);
- c.setelem(2,1,-2.1);
- c.setelem(2,2,5.2);
- c.setelem(3,1,-3.3);
- c.setelem(3,2,6.4);
- cout<<"A矩阵:"<<endl; a.print();
- cout<<"B矩阵:"<<endl; b.print();
- cout<<"C矩阵:"<<endl; c.print();
- d=a+b;
- cout<<"A+B矩阵:"<<endl; d.print();
- d=a-b;
- cout<<"A-B矩阵:"<<endl; d.print();
- e=a*c;
- cout<<"A*C矩阵:"<<endl; e.print();
- }