I have a 1D array that is treated as a 2D (long story). Is there a way to get calls like array[i][j] work? operator[][] (int x, int y) gives me a syntax error...
Printable View
I have a 1D array that is treated as a 2D (long story). Is there a way to get calls like array[i][j] work? operator[][] (int x, int y) gives me a syntax error...
If it is indeed a 1d array then id have to say it cant be called using [][] what would the second be pointing to? Can you give us a better example of what your trying to do? Why you want a 1d array to be treated as a 2d array?
Well, you can overload () for it and by that way treat it as 2D. And as I said, it's a long story...
Foundations:
You have a class. This class should be indexable by double index ( [i][j] ). As a single operator, as you have experienced, it isn't possible. However, if you think it's worth the time, you can do the following:
Create a function that does what you need as a normal member function "Indexer( int x, int y )".
Create a single indexer ( [] ), that returns another object of a user defined class. This class defines another indexer that returns the parents class' Indexer function.
Example:
I've no compiler handy... so this is just an educated guess ;)PHP Code:
#include <stdio.h>
class UsesDoubleIndexer
{
public:
class dblidx
{
private:
int m_x;
UsesDoubleIndexer* m_Parent;
public:
dblidx( int x, UsesDoubleIndexer* Parent )
{
m_x = x;
m_Parent = Parent;
}
int operator [] ( int y )
{
return m_Parent.Indexer( m_x, y );
}
}
dblidx operator [] ( int x )
{
return dblidx( x, this );
}
int Indexer( int x, int y )
{
// your indexer function here
return 2*x+y;
}
};
int main()
{
UsesDoubleIndexer udi;
printf("%d", udi[0][3] );
return 0;
}