#ifndef DIAGONALMATRIX_H
#define DIAGONALMATRIX_H
#include "illegalParameterValue.h"
#include "matrixIndexOutOfBounds.h"
template<typename T>
class diagonalMatrix
{
public:
diagonalMatrix(int theN = 10);
~diagonalMatrix() {delete [] element;}
T get(int, int) const;
void set(int, int, const T&);
private:
int n; // 矩阵维度
T *element; // 储存对角矩阵的一维数组
};
template<typename T>
diagonalMatrix<T>::diagonalMatrix(int theN)
{// 构造函数
// 检验 theN 的值是否有效
if (theN < 1)
throw illegalParameterValue("Matrix size must be > 0");
n = theN;
element = new T[n];
}
template<typename T>
T diagonalMatrix<T>::get(int i, int j) const
{// 返回矩阵中(i, j)位置上的元素
// 检验 i 和 j 的值是否有效
if (i < 1 || j < 1 || i > n || j > n)
throw matrixIndexOutOfBounds();
if (i == j)
return element[i - 1]; // 对角线上的元素
else
return 0; // 非对角线上的元素
}
template<typename T>
void diagonalMatrix<T>::set(int i, int j, const T& newValue)
{// 储存(i, j)项的新值
// 检查 i 和 j 的值是否有效
if (i < 1 || j < 1 || i > n || j > n)
throw matrixIndexOutOfBounds();
if (i == j)
// 储存对角元素的值
element[i-1] = newValue;
else
// 非对角元素的值必须是0
if (newValue != 0)
throw illegalParameterValue("nodiagonal elements mus be zero");
}
#endif // !DIAGONALMATRIX_H
数据结构-类 diagonalMatrix
最新推荐文章于 2024-07-21 21:32:15 发布