// overload_array.cpp
// overloading the c++ array subscript operator []
#include <iostream>
usingnamespace 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;
}
It does not return the value. It returns a reference (&) to the value, so that on line 34 it is possible to assign a value. Remove the & on line 12 and see what happens.
internal compiler error: in gen_type_die_with_usage, at dwarf2out.c:19483
in my codeblocks with support for C++11 turned on.
I assume that by my understanding in a two dimensional array the first index stores pointer to starting address of the arrays, the second index access the pos element in the array.
The overloaded operator returns a reference to 'array of 10 int'. ie. a[3] yields a reference to 'array of 10 int'.
The [5] in a[3][5] is the normal subscript operator applied to that array,.