【问题标题】:C++ How can I write a method that takes two matrices and calculates the number of rows and columnsC ++如何编写一个采用两个矩阵并计算行数和列数的方法
【发布时间】:2021-09-08 22:59:39
【问题描述】:

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

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

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;
}

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

【问题讨论】:

  • 是什么让你停止做你想做的事?问题是什么?
  • 将最近创建的矩阵的大小存储在静态变量中不是问题吗?
  • 问题是如何在此方法之外访问变量 nRow 和 nCol。如果只创建一个方法,我可以简单地编写一个返回它们的方法,但如果创建了两个,它只返回最新的行和列。
  • 正确。你不能,用这种方法。你需要改变它。
  • 我建议使用std::vector 而不是new[]

标签: c++ arrays class matrix methods


【解决方案1】:

这些类型的典型形状是这样的

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 实例的角色。使用这种方法可以发现(或学习)很多边缘情况,所以玩得开心:)

【讨论】:

  • 抱歉,我仍然不明白这将如何让我访问行和列。
  • 一旦你有一个名为matMatrix&lt;T&gt; 实例,你可以调用mat.rows() 来查看特定对象包含多少行。
  • 我已经有一个方法` unsigned int rows() const { return m_nRows; }`,问题是它只返回最新的矩阵行。我想在课堂上调用它。顺便说一句,谢谢你的时间!
  • 对,但你的引用 static m_nRows,它实际上是一个全局变量。在我的示例中,它引用了Matrix&lt;T&gt; 对象的实例变量,其中可以有任意多个。
  • 然后你打电话给this-&gt;rows() 或者只是rows()。花一些时间重新审视你曾经学习过的任何材料中的实例方法的细节。
猜你喜欢
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 2017-06-13
  • 1970-01-01
  • 2019-11-13
相关资源
最近更新 更多