这个主要是C++ 11的练习项目,实现一个矩阵类,并实现简单的矩阵运算,不需要用到复杂的运算符重载,以及底层复杂并行等算法,这不是重点。
开发IDE使用Clion,调试能力(断点调试)比较弱,需要加强。
实现矩阵基类:
知识点:C++构造和析构函数,以及线性动态内存分配,纯虚函数,protected关键字,模版。
template <typename T>
class Matrix {
protected:
Matrix(int r, int c):rows(r),cols(c),linear(new T[r*c]) {
for(int i=0;i<r*c;i++) { linear[i] = 0;}
}
// # of rows in the matrix
int rows;
// # of Columns in the matrix
int cols;
// Flattened array containing the elements of the matrix
// Allocate the array in the constructor. Don't forget to free up
// the array in the destructor.
T *linear;
public:
// Return the # of rows in the matrix
virtual int GetRows() = 0;
// Return the # of columns in the matrix
virtual int GetColumns() = 0;
// Return the (i,j)th matrix element
virtual T GetElem(int i, int j) = 0;
// Sets the (i,j)th matrix element to val
virtual void SetElem(int i, int j, T val) = 0;
// Sets the matrix elements based on the array arr
virtual void MatImport(T *arr) = 0;
virtual ~Matrix(){
delete [] linear;
}
};
行优先存储的矩阵基类,二维数组的动态内存分配以及回收,指针数组。
思考一个问题:在这个实现中,二维数组和一维数组是共用内存的吗?
template <typename T>
class RowMatrix : public Matrix<T> {
public:
RowMatrix(int r, int c) : Matrix<T>(r, c) {
data_ = new T* [r];
for(int i=0;i<r;i++){
data_[i]