在矩阵类中使用[] []进行常量双索引 [英] Const Double Indexing with [][] in Matrix Class

查看:86
本文介绍了在矩阵类中使用[] []进行常量双索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码包含一个简单的Matrix类示例,并使用'proxy'Row类启用了双索引[] [].

The following code contains a simple example of a Matrix class, with double indexing [][] enabled using a 'proxy' Row class.

#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 Matrix进行双重索引.例如,当包含最后一行时,以下代码无法编译.

However, this doesn't allow double indexing of a const Matrix. For example, the below code fails to compile when the last line is included.

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对象进行双索引?

So the question is, how can I modify my Matrix class to allow for double indexing of const Matrix objects?

推荐答案

由于bconst矩阵,因此您需要添加const版本的索引运算符.

Since b is a const Matrix, you need to add const versions of your indexing operator.

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

这将需要对Row类(或第二个代理类)进行其他更改,以处理operator[]const Matrix &const重载.

This will require additional changes to the Row class (or a second proxy class) to handle the const Matrix & and const overload of operator[].

这篇关于在矩阵类中使用[] []进行常量双索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆