如何重载数组索引操作符为2D数组的包装类? [英] How to overload array index operator for wrapper class of 2D array?

查看:99
本文介绍了如何重载数组索引操作符为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
} 



我认为不可能重载[] []。

I think directly it not possible to overload [][] .

我想我必须间接做,但是如何实现呢?

I think i have to do it indirectly but how to implement it?

推荐答案

更容易的解决方案是使用operator(),因为它允许多个参数。

The easier solution is to use the operator() as it allows multiple parameters.

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;

简单的方法是第一个operator []返回一个中间对象,

The easy way is that the first operator[] returns an intermediate object that the second operator[] returns the value from the array.

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;

这篇关于如何重载数组索引操作符为2D数组的包装类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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