微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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
}

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

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

解决方法

更简单的解决方案是使用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;

简单的方法是第一个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;

原文地址:https://www.jb51.cc/c/110308.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐