【问题标题】:How to overload [][] operator for the class representing dynamically allocated 2d array [duplicate]如何为表示动态分配的二维数组的类重载[] []运算符[重复]
【发布时间】:2013-01-17 04:12:37
【问题描述】:

可能重复:
Operator[][] overload

我创建了一个类,其中包含一个数组,其中包含(在一行中)给定二维数组中的所有数字。例如:{{1,2}{3,4}} bT 的对象中的字段包含 {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);

    };

【问题讨论】:

标签: c++ operator-overloading


【解决方案1】:

你不能。您必须重载 operator[] 才能返回 proxy 对象,然后重载 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&amp; 中保存 T&amp;,这取决于您。

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

【讨论】:

  • 或者您也可以选择不同的语法,例如 obj(i,j)obj[{i,j}]
  • 考虑到这一点,只需编写一个get(int,int) 函数或重载operator()(int,int) 就会少很多麻烦。
  • @BenjaminLindley 如何重载()运算符,在任何地方都找不到
  • @RobertKilar:我回答了你问的一个问题,展示了如何超载operator()here
  • @RobertKilar: 我不能关注你...operator() 不需要是static...(?)operator() 只是一个成员函数,可以访问你类中的非静态字段...请阅读我在aforementioned thread中发布的代码,并意识到operator()成员函数也可以访问非静态数据成员。
【解决方案2】:

在二维数组的情况下,您不需要创建代理类型。只需使用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";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 2016-03-31
    • 2018-01-04
    • 1970-01-01
    • 2019-07-25
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多