C ++:我自己类型

时间:2015-10-13 02:32:45

标签: c++ arrays multidimensional-array

您好,我正在编写一个简单的程序,它基本上是任何数据类型的3D数组的模板。要求稍后在main函数中可以直接访问数组的元素(即[1] [2] [3] = 3;可以在没有警告的情况下使用)。以下是我到目前为止的情况:

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];
}

但是现在我得到了这个错误:重载operator []必须是二元运算符(有4个参数)。我尝试将其更改为

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

但后来我得到错误:operator []不能是变量或数据成员的名称。所以我现在还不确定该怎么做。 谢谢!

编辑:

主要功能是(是的,它是一个家庭作业):

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;
}

所以我必须在这里使用[i] [j] [k]。

1 个答案:

答案 0 :(得分:0)

&#34;代理类&#34;评论中提到的是最标准的方法。

然而,因为这只是你的功课,如果你 只想在T**中使用它,然后您只需返回T** operator[](const int x) { return tempArray[x]; }

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorPrimary</item>      
</style>