首页 > 解决方案 > C ++如何编写一个采用两个矩阵并计算行数和列数的方法

问题描述

我正在编写一个矩阵处理类来练习该语言。

我的第一个方法是这样的:

template<typename T>
T* matrixClass<T>::CreateMat(unsigned int nRow, unsigned int nCol, T& num)
{   
    
    matrixClass::m_nRows = nRow; //number of rows
    matrixClass::m_nCol = nCol;  //number of columns

    matrix = new T[nRow * nCol];//memory allocation
    for (unsigned int row = 0; row < nRow; row++) //row selection N x m
    {
        for (unsigned int col = 0; col < nCol; col++)
        {
            matrix[col + row * nCol] = num;   //assigns data to columns n x M
            num += 1.1;
        }
    }

    return matrix;
}

我正在尝试在同一个类中编写一个方法,该方法采用此方法创建的两个矩阵并找到它的 rows 和 columns 。

标签: c++arraysclassmatrixmethods

解决方案


这些类型的典型形状类似于

template <class T>
class Matrix {
  private:
  unsigned int m_nRows, m_nCols;
  T* m_Data;

  public:
  Matrix() = delete;
  Matrix(unsigned int nRow, unsigned int nCol, T* src = nullptr);
  Matrix(const Matrix& orig);
  Matrix(Matrix&& orig);
  Matrix& operator=(const Matrix& orig);
  Matrix& operator=(Matrix&& orig);
  ~Matrix();

  unsigned int rows() const { return m_nRows; }
  unsigned int columns() const { return m_nCols; }
}

...或将构造函数设为私有并createMat接管构造Matrix实例的角色。使用这种方法可以发现(或学习)很多边缘案例,所以玩得开心:)


推荐阅读