1

I know that it's possible to overwritew index operation [] in C++ and work with class internal data like with an array. Is it possible to overwrite [][] and to work like with two demension array ?

4 Answers4

2

Yes, it's possible (and std::vector is an example of such a class).

You should overload operator[] in your class or structure.

In case you use positive integers to index data possible signature will be:

RETURN_TYPE operator[] (size_type n);

UPD: if you want two-dimensional data structure with non-negative integers as keys you can use vector of vectors:

std::vector<std::vector<YOUR_TYPE>> vector_name;
sasha.sochka
  • 14,395
  • 10
  • 44
  • 68
1

In order to achieve it you need to overload operator[] to return some object that have operator[] too. For example:

class Proxy {
     std::vector<int>::iterator it;
     //constructor;
     int operator[] (size_t pos) {
         return *(it + pos);
     }
}

class MyMatrix {
    std::vector<std::vector<int>> v;
    Proxy operator[] (size_t pos) {
        return Proxy(v[pos].begin());
    }

}
RiaD
  • 46,822
  • 11
  • 79
  • 123
  • 1
    Note that if you're not doing bounds checking, and you use a single dimension implementation, a pointer is an adequate `Proxy`: `int* operator[]( int i ) { return &v[ i * columns ]; }`. Similarly, if with your implementation, `std::vector&` is a suitable proxy. – James Kanze Jun 24 '13 at 16:39
0

Yes indeed you can; conventionally, you would overload [] return a reference to a row-type object, and overload [] on that row-type object to yield a reference to the scalar.

You should also consider overloading pointer dereference as well in order to maintain the equivalence of [x] and *(... + x).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

Let's say you have an array arr whenever you want to acess arr[x][y] for exemple it has an equivalence of (arr[x])[y] so first of all arr[x] is evaluated (let's name it a) and then a[y] is evaluated so you have to overload just []operator.

Alexandru Barbarosie
  • 2,952
  • 3
  • 24
  • 46