0

Hi I'm writing a simple program which is basically a template for a 3D array of any data type. It is required that later on in the main function the element of the array can be accessed directly (i.e. a[1][2][3] = 3; can be used without warnings). Here is what I have so far:

template <class T>
class CArray3D {
public:
    T*** tempArray;
CArray3D(int x,int y,int z){
    tempArray = new T**[x];
    for(int i=0;i<x;i++) {
        tempArray[i] = new T*[y];
        for(int j=0;j<y;j++) {
            (tempArray)[i][j] = new T[z];
        }
    }
};
T& operator[](const int x,const int y,const int z);

};


template <class T>
T& CArray3D<T>::operator[] (const int x,const int y,const int z) {
    return tempArray[x];
}

But now I get this error: overloaded operator[] must be a binary operator (has 4 parameters). I tried changing it to

operator[][][](const int x, const...) 

but then I get the error: operator[] cannot be the name of a variable or data member. So I'm not sure how to do it now. Thank you!

EDIT:

The main function is given (yeah it's a homework):

int main() {
CArray3D<int> a(3,4,5);
int No = 0;
for(int i=0;i<3;i++)
    for(int j=0;j<4;j++)
        for(int k=0;k<5;k++)
            a[i][j][k] = No++;

for(int i=0;i<3;i++)
    for(int j=0;j<4;j++)
        for(int k=0;k<5;k++)
            cout << a[i][j][k] << ",";

return 0;
}

So I have to use a[i][j][k] here.

richards
  • 517
  • 9
  • 27
  • 3
    Read about "proxy classes". Also, use a 1D array for storage, as this guarantees contiguous memory and hence it will be faster than using pointers to pointers. Related: http://stackoverflow.com/questions/6969881/operator-overload – vsoftco Oct 13 '15 at 02:37
  • Please take a look at the linked question in my previous comment, it explains how to do it for a 2D array. You can then extend it to 3D. – vsoftco Oct 13 '15 at 03:09

1 Answers1

0

The "proxy class" mentioned in the comment is the most standard method.

However since this is only your homework, and if you just want to use it in main(), then you can just return a T**.

T** operator[](const int x) {
    return tempArray[x];
}
johnjohnlys
  • 394
  • 1
  • 9