c – 如何为2D数组的包装类重载数组索引运算符?

前端之家收集整理的这篇文章主要介绍了c – 如何为2D数组的包装类重载数组索引运算符?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
#define ROW 3
#define COL 4

class Matrix
{
   private:
      int mat[ROW][COL];  
    //.....
    //.....

};

int main()
{
  Matrix m;
  int a = m[0][1]; //  reading
  m[0][2] = m[1][1]; // writing
}@H_301_3@ 
 

我认为直接不能超载[] [].

我想我必须间接地做,但如何实现它?

解决方法

更简单的解决方案是使用operator(),因为它允许多个参数.
class M
{
    public:
       int& operator()(int x,int y)  {return at(x,y);}
    // .. Stuff to hold data and implement at()
};


M   a;
a(1,2) = 4;@H_301_3@ 
 

简单的方法是第一个operator []返回一个中间对象,第二个operator []返回数组中的值.

class M
{
    public:
    class R
    {
         private:
             friend class M; // Only M can create these objects.
             R(M& parent,int row): m_parent(parent),m_row(row) {}
         public:
              int& operator[](int col) {return m_parent.at(m_row,col);}
         private:
              M&  m_parent;
              int m_row;
    };

    R operator[](int row) {return R(*this,row);}

    // .. Stuff to hold data and implement at()
};

M   b;
b[1][2] = 3;   // This is shorthand for:

R    row = b[1];
int& val = row[2];
val      = 3;@H_301_3@
原文链接:https://www.f2er.com/c/110308.html

猜你在找的C&C++相关文章