Originally Posted by
Polymorphic OOP
so you have 2 options.
There is yet another option that is very elegant for the end user, but requires more work on your end.
If you create a nested class/struct within your class that represents the second dimension of the data, you can achieve the desired behavior.
Let me explain by pseudo-code example. Lets create a class called TwoD which stores FOO objects in an array called FooArray.
We wish to offer access to our FooArrary data-member through variable.[1][1] syntax.
Code:
const int WIDTH = 20;
const int HEIGHT = 20;
Class TwoD
{
private:
FOO [WIDTH * HEIGHT];
BAR [HEIGHT][WIDTH]; /* order doesn't matter. The important thing is that you pick one way of viewing the order. X,Y is just as correct as Y,X as long as you're consistant. */
struct OneDFoo
{
FOO* sourceArrary; //data-member
OneD(FOO* source) : sourceArray(source) {}; /* constructor, which stores the source array to index into when subscript operator is called */
FOO& operator[](int index) //Operator for second level of indirection
{
return sourceArray[index];
}
}//end of OneDFoo struct
public:
//Constructor & Destructor...
FOO& operator[](int index)
{
int offset = index*WIDTH; /* we multiply the first index by the number of indecies wide the array is so that we are moved into the array the proper "height" and can now continue indexing to locate the "width" */
OneDFoo temp(&FOO[offset]); /* initialize the one-d portion with the address of the array starting from the proper height (offset) */
return temp[index]; /* use the subscript operator of the OneDFoo struct, which will navigate index number of FOO objects over, and return the one that was found, which we then return out of the whole class */
}
//other methods...
//Example with the BAR data-member
struct OneDBar
{
BAR* sourceArrary; //data-member
OneD(BAR* source) : sourceArray(source) {}; /* constructor, which stores the source array to index into when subscript operator is called */
BAR& operator[](int index) //Operator for second level of indirection
{
return sourceArray[index];
}
}//end of OneDBar struct
public:
//Constructor & Destructor...
BAR& operator[](int index)
{
OneDBar temp(BAR[index]); /* THIS IS THE SIGNIFICANT DIFFERENCE FROM THE FOO EXAMPLE */
return temp[index];
}
}//end of TwoD class
I can't guarentee this has no typos, or that it will compile as I only meant to provide a usefull pseudo-code like example.
Also this is more verbose than I would actually implement it, which was done on purpose to explain things, as well
this only covers non const operator [] you will need also need to implement the const version unless your project does not
require it, and finally in the real world this would be templatized.
Hope this provides insight.