Skip to main content
gamedev.net
🔒 Locked

operator[][] ?

Started by mictian Jan 30, 2003 at 7:09 PM 3 replies 250+ views
Original Post
mictian
mictian
Greetings, Does anybody know if it is possible to create an operator to handle an array access with multiple subscripts? i have something like this already: float & operator[] ( int n ) { return( m[ n ] ); } but i want a similar thing for a two dimensional array access...is this possible? Thanks
¿We Create World?
DerekSaw
DerekSaw
No. Use operator() instead for multi-subscript
"after many years of singularity, i'm still searching n the event horizon" o
Extrarius
Extrarius
It IS possible, but its messy. You have to make operator [] return an object that also has [] defined, so when you type object[][] its using the [] operator of two different objects. Real messy.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
bmarci
bmarci
not as messy as it seems

eg: you have a class CDATA which contains an array:
int [ARRAYSIZE_X][ARRAYSIZE_Y]

It must be divided into 2 classes:


class CDATA2 {
int items[ARRAYSIZE_X];
public:
int& operator[](int x);
};
class CDATA {
CDATA2 lines[ARRAYSIZE_Y];
public:
CDATA2& operator[](int y);
};


CDATA x; // CDATA2 is a "subclass"

now you can access the values like this
x[col][row]


[edited by - bmarci on February 3, 2003 10:42:21 AM]
Brother Bob
Brother Bob
Why mess with double classes? Just return a pointer to a 1D array in the 2D array, and dereference this pointer as usual.

  
class my4x4array
{
public:
int *operator[](int n) {return data[n];}
private:
int data[4][4];
};
...
my4x4array foo;

foo[2][3] = 0xdeadbeef;

Maybe I''m missing something important with this way though. Anyways, I prefer operator().

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.