如何为表示动态分配的 2d 数组的类重载 [][] 运算符

How to overload [][] operator for the class representing dynamically allocated 2d array

本文关键字:运算符 重载 数组 2d 表示 动态分配      更新时间:2023-10-16

可能的重复项:
运算符 [][] 重载

我已经制作了一个包含(一行)给定 2d 数组中所有数字的数组的类。 例如给定:{{1,2}{3,4}}T 的对象中的b字段包含{1,2,3,4} 。我想为这个类重载 [][] 运算符,这样它就会像那样工作

T* t.....new etc.
int val = (*t)[i][j]; //I get t->b[i*j + j] b is an 1dimension array

    class T{
    public:
        int* b;
        int m, n;
        T(int** a, int m, int n){
            b = new int[m*n];
            this->m = m;
            this->n = n;
            int counter = 0;
            for(int i  = 0; i < m; i++){
                for(int j = 0; j < n; j++){
                    b[counter] = a[i][j];
                    counter++;
                }
            }
        }
int main()
{
    int m = 3, n = 5, c = 0;
    int** tab = new int*[m];
    for(int i = 0; i < m; i++)
           tab[i] = new int[n];
    for(int i  = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            tab[i][j] = c;
            c++;
            cout<<tab[i][j]<<"t";
        }
        cout<<"n";
    }

    T* t = new T(tab,3,5);
    };

你不能。您必须重载operator[]才能返回代理对象,而代理对象又重载operator[]以返回最终值。

像这样:

class TRow
{
public:
    TRow(T &t, int r)
    :m_t(t), m_r(r)
    {}
    int operator[](int c)
    {
        return m_t.tab[m_t.n*m_r + c];
    }
private:
    T &m_t;
    int m_r;
};
class T
{
    friend class TRow;
    /*...*/
public:
    TRow operator[](int r)
    {
         return TRow(*this, r);
    }
};

与其将T&保存在TRow中,不如直接保存指向该行的指针,这取决于您。

此解决方案的一个很好的功能是您可以将 TRow 用于其他事情,例如 operator int*() .

对于 2D 数组,无需创建代理类型。只需使用int*

#include <iostream>
class T {
public:
  int m, n;
  int *b;
  T(int m, int n) : m(m), n(n), b(new int[m*n]) {
  }
  int*operator[](std::size_t i) {
    return &b[i*m];
  }
};
int main () {
  T t(2,2);
  t[0][0] = 1;
  t[0][1] = 2;
  t[1][0] = 3;
  t[1][1] = 4;
  std::cout << t.b[0] << t.b[1] << t.b[2] << t.b[3] << "n";
}