我想做什么: 我想知道如何在 C++ 中将类用作一种“内置”数组(C 也是可以接受的)。所以,基本上我希望能够做到这一点:
array1d rows(5);
//an integer array of length 5 - iniatilized to 0 upon instantiation.
//rows can be imagined as this: [ 0, 0, 0, 0, 0 ]
array1d x(1), y(2), z(3);
array2d cols(3);
cols[0] = x;
cols[1] = y;
cols[2] = z;
//an array of array of integers [ [x] [y] [z] ]
//where x, y and z are of type array1d, so here is what it would like:
//if x = 1, y = 2, z = 3
//[ [0], [0, 0], [0, 0, 0] ]
array3d depth(2);
//an array of array of array of integers [ [cols] [cols] ]
//where cols is of type array2d, so when expanded it would like:
//[ [ [0], [0, 0], [0, 0, 0] ]
// [ [0], [0, 0], [0, 0, 0] ] ]
到目前为止我所拥有的
using namespace std;
class array3d;
class array2d;
class array1d//works exactly the way i want it to
{
int len;
int *data;
public:
array1d (int size){
data = new (nothrow) int[size];
if (data != 0){
len = size;
for (int i = 0; i<len; i++){
data[i] = -1;
}
}
}
~array1d (){
delete data;
}
void print(){
for (int i = 0; i<len; i++){
cout << data[i] << " ";
}
cout << endl;
}
int operator[] (int index){
if (index >= 0 && index <= len){
return data[index];
}
}
friend class array2d;
};
class array2d//this is what needs changing
{
int len;
array1d *data;
public:
array2d (int size_dim1, int size_dim2){
data = new (nothrow) array1d[size_dim1]; //i think the problem is here
if (data !=0){
len = size_dim1;
for (int i = 0; i < len; i++){
data[i] = array1d(size_dim2);
}
}
}
~array2d (){}
void print(){
for (int i = 0; i < len; i++){
data[i].print();
}
}
array1d operator[] (int index){
return data[index];
}
friend class array3d;
};
class array3d//dont even know how to get this one started
{
array3d (int size_dim1, int size_dim2, int size_dim3){
data = new (nothrow) array2d[size_dim2, size_dim3];
if (data !=0){
len = size_dim1;
for (int i = 0; i < len; i++){
data[i] = array2d(size_dim2, size_dim3);
}
}
}
~array3d (){}
//overload [] operator
private:
int len;
array2d *data;
};
我还希望能够添加更多类以适应可能的 4 维,这样我就不必每次添加另一个类时都进行自定义。