CMU 15-445/645 2020 Project0 C++11实现矩阵类的练习项目

这个主要是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] 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值