Hey. i have a class with 2D array inside. I'd like to overload [] operator that will allow me to access any member of this array (like int a=myarr[1][2]). How can i do that? thanks.
This would allow you to put bounds checking on X and Y before trying to access your array. Allow you to prevent out of bounds exceptions and memory issues.
I don't agree with Zaita. You can do all the bounds checking in an operator [], just like another function.
It's not possible to overload "operator[][]". You have to overload "operator[]", and return some kind of proxy object, that also overload "operator[]" to get the second index.
Draft code:
1 2 3 4 5 6 7 8 9 10 11 12
class Array {
int** data;
public:
class Proxy {
Array& _a;
int _i;
public:
Proxy(Array& a, int i) : _a(a), _i(i) {}
int& operator[](int j) { return _a.data[_i][j]; }
};
Proxy operator[](int i) { return Proxy(this, i); }
};
ropez, why did you set the "Proxy" class as a public of "Array"? Can't it be a private one? And some newbie question: what is "_" char doing before "a" and "i"? Thanks you for help.
Zaita, when I overload operator() should i use int a = myClass->getValue(X, Y);
and not just int a = myClass(X,Y);?