Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

operator[][] ?

This topic is 5587 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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().

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!