码迷,mamicode.com
首页 > 其他好文 > 详细

矩阵类

时间:2016-05-05 09:40:57      阅读:101      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!