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

Possible duplicate:
Operator [] [] overload

I created a class that contains an array containing (on one line) all the numbers from a given 2d array. For example: a {{1,2}{3,4}}

field b

in a class object T

contains {1,2,3,4}

. I would like to overload the [] [] operator for this class so that it works like

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);

    };

      

+3


source to share


2 answers


You can not. You need to overload operator[]

to return the proxy object, which in turn overloads operator[]

to return the final value.

Something like:

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);
    }
};

      



Instead of saving T&

to, TRow

you can store directly the pointer to the string, which is up to you.

The nice thing about this solution is that you can use TRow for other things like operator int*()

.

+4


source


In case of 2d array, you don't need to create proxy type. Just use 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";
}

      

+1


source







All Articles