c++ - 在 Matrix 类中使用 [][] 进行常量双索引

标签 c++ c++11 matrix operator-overloading

以下代码包含一个 Matrix 类的简单示例,使用“代理”Row 类启用双索引 [][]。

#include <valarray>
#include <iostream>

template <typename T>
class Matrix {

private:

  // Data members
  int nRows_;
  int nColumns_;
  std::valarray<T> data_;

public:

  // Constructor
  Matrix(const int nRows,
         const int nColumns)
    : nRows_{nRows},
      nColumns_{nColumns},
      data_{std::valarray<T>(nRows*nColumns)} {}

  // Row friend class to enable double indexing
  class Row {   
    friend class Matrix;

  private:

    // Constructor
    Row(Matrix& parent,
        int row)
      : parent_{parent},
        row_{row} {}

    // Data members
    Matrix& parent_;
    int row_;

  public:

    // Index columns
    T& operator[](int column) {
      int nColumns{parent_.nColumns_};
      int element{row_*nColumns + column};
      return parent_.data_[element];
    }
  };

  // Index rows
  Row operator[](int row) {
    return Row(*this, row);
  }
};

但是,这不允许对 const 矩阵进行双重索引。例如,当包含最后一行时,下面的代码无法编译。

int main() {

  Matrix<int> a{3,3};
  const Matrix<int> b{3,3};
  std::cout << a[1][2];
  std::cout << b[1][2];
}

所以问题是,如何修改我的 Matrix 类以允许对 const Matrix 对象进行双重索引?

最佳答案

由于 b 是一个 const 矩阵,您需要添加索引运算符的 const 版本。

Row operator[](int row) const { ... }

这将需要对 Row 类(或第二个代理类)进行额外更改,以处理 const Matrix &const 重载运算符[]

关于c++ - 在 Matrix 类中使用 [][] 进行常量双索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49822848/

相关文章:

c - 如何将产品行迭代到 C 中的列

c# - 使用 LinQ 将一系列值添加到列表中

c++ - 构造函数被调用两次

c++ - 为什么 'std::vector<int> b{2};' 创建一个 1 元素 vector ,而不是 2 元素 vector ?

c++ - 有人能解释一下如果在堆上分配对象数组的过程中抛出异常会发生什么吗?

带返回的 C++ 析构函数

c++ - 根据条件将元素从一个 forward_list 转移到另一个

python - 对称寻址矩阵

c++ - 文件异常处理

c++ - 在 "if"语句中创建 COM 智能指针时出现错误 C2275