overloading operator [ ]

Hi all! I'd like to overload operator [ ], but I don't know the sintax to do so.

Suppose I have a class like:

1
2
3
4
class myArray {
    int size;
    int a[100];
};


How can I overload [ ] so that I can do something like:

1
2
3
myArray x;
x[1] = 2;  // map x[i] into x.a[i]
cout << x[1] << endl;


Regards
Apart from reducing the size of the class array to 10 elements JUST to make the array output function easier to grasp, the following should help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// overload_array.cpp
// overloading the c++ array subscript operator []
#include <iostream>

using namespace std;

class myArray {
    private:
      int size;
      int a[10];
    public:
      int& operator[] (int x) {
          return a[x];
      }
      void print_array();   // I included this just to show the operator[] works!   
};

void myArray::print_array()
{
    for (int j=0; j < 10; j++)
        cout << "array[" << j << "] = " << a[j] << "\n";
}

int main(int argc, char *argv[])
{
    // create an instance of the myArray class    
    myArray instance;

    // load instance.a[] with integers
        // NOTE: here we use instance[i] NOT instance.a[i]   
        // instance.a[] wouldn't work as "int a[]" in the myArray class
        // is defined as PRIVATE!!!!!  
    for (int i=0; i < 10; i++)
        instance[i] = i; 

    // show that our operator worked by printing out the array values
    // using the myArray member function myArray::print_array()
    instance.print_array();

    cout << "\n\n";
    system("PAUSE");
    return EXIT_SUCCESS;
}

Last edited on
make it inline as well.
Topic archived. No new replies allowed.