首页 > 其他 > 详细

矩阵类

时间:2016-05-05 09:37:52      阅读:158      评论:0      收藏:0      [点我收藏+]

class MatrixBase
{
int rows, cols;
public:
MatrixBase(int the_rows, int the_cols) :rows(the_rows), cols(the_cols){}
int GetRows()const { return rows; }
int GetCols()const { return cols; }
virtual double getElement(int r, int c)const = 0;
void show()
{
for (int i = 0; i < rows;i++)
{
cout << endl;
for (int j = 0; j < cols; j++)
cout << getElement(i, j)<< " ";
}
}
};

class Matrix :public MatrixBase
{
double *val;
public:
Matrix(int rows, int cols, double m[] = NULL) :MatrixBase(rows, cols)
{
val = new double[rows*cols];
for (int i = 0; i < rows*cols; i++)
val[i] = (m == NULL ? 0.0 : m[i]);
}
~Matrix(){ delete[] val; }
double getElement(int r, int c)const { return val[r*GetCols() + c]; }
};

class UnitMatrix :public MatrixBase
{
public:
UnitMatrix(int rows) :MatrixBase(rows, rows){}
double getElement(int r, int c)const
{
if (r==c) return 1.0;
return 0.0;
}
};

int main()
{
MatrixBase *m;
double d[][5] = { { 1, 2, 3, 4, 5 }, { 2, 3, 4, 5, 6 }, { 3, 4, 5, 6, 7 } };
m = new Matrix(3, 5, (double *)d);
m->show();
delete m;
cout << endl;
m = new UnitMatrix(5);
m->show();
delete m;
return 0;
}

矩阵类

原文:http://www.cnblogs.com/huninglei/p/5460502.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!