Skip to main content
gamedev.net
🔒 Locked

[] operator overloading

Started by Outworlder Sep 27, 2000 at 8:34 AM 2 replies 250+ views
Original Post
Outworlder
Outworlder
I want to overload the operator [] to add some safety checks to my dynamic generated arrays. So I could use something like:

Ctile* operator[] (int i);

 
That works fine. But what if I want to use more than one dimension? I''ve tried:

Cmap_cell* operator[][] (int x,int y); // no luck

Cmap_cell* operator[] (int x, int y); // Nope...

 
So how do I implement this? The book I have does''nt say anything about more than one dimension Gaiomard Dragon -===(UDIC)===-
Gaiomard Dragon-===(UDIC)===-
Atavist
Atavist
Okay, this question has come up before. Ill show you a really nice way of doing this. The basic idea is you build a class inside your class and use this as an intermediate value, keep the inner class small and theres hardly no performance hit to speak of.

Anyway here's the code:
            
#include<iostream>
using namespace std;

class matrix
{
class row
{
int* m_r;//change this to a map cell pointer

public:
row(int* r) {m_r = r;}//change r to a cell pointer too

int& operator [] (int index)//change the return val to a cell refrence

{
return m_r[index];
}
};
int m_array[10][10]; //change this to a mapCell array

public:
row operator [] (int index)
{
return row(m_array[index]);
}
};

int main()
{
matrix a;
a[5][2] = 4;
cout <<a[5][2] <<endl;

return 0;
}


I think therefore I code.

Edited by - Atavist on September 27, 2000 11:53:51 AM
Just because the church was wrong doesn't mean Galileo wasn't a heretic.It just means he was a heretic who was right.
pogo
pogo
You don''t really need to do anything. Take this class for example (I''ll use a static array, but it will work the same with dynamic arrays as long as you allocate them properly, and not in the array-of-pointers-to-array method):

class Foo
{
private:
int data[100][100];
public:
int* operator[](int i)
{
return(data);
}
};

That''s all you need.

When you try to do the following:

Foo bar;
int x = bar[10][20];

the operator[] function returns the address of bar[10] and then dereferences that address + 20. Like ((int*)bar[10])[20].


You can think of it like this:

Foo bar;
int* ptr;
int x;

ptr = bar[10];
x = ptr[20];

But it does it all in one quick step.




Wilka
Wilka
quote:

You don''t really need to do anything. Take this class for example...



Outworlder said "I want to overload the operator [] to add some safety checks to my dynamic generated arrays", so that method wouldn''t work - you don''t get any extra safety other than the first dimension. So the small nested class is a better choice.

Topic Locked

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

Sign in to reply to this topic.