在C ++中的构造函数内创建2D数组

时间:2014-12-23 15:15:00

标签: c++ arrays constructor

我正在尝试执行以下操作:

class Test{
private:
    int x;
    int y;
    // Create array[][] here
public:
    Test(const int x, const int y){
        this->x = x;
        this->y = y;
        // set: array[x][y] here
    }
};

如您所见,我想创建一个2d-Array,而边界将在构造函数中给出。 我怎样才能做到这一点?

它适用于通常的数组:

class Test{
private:
    int x;
    int y;
    int *array;
public:
    Test(const int x, const int y){
        this->array = new int[x]; // works
        // this->array = new int[x][y] does not work
        this->x = x;
        this->y = y;
    }
};

2 个答案:

答案 0 :(得分:0)

你应该考虑用指针分配内存,应该如下:

class Test{
private:
    int x;
    int y;
    int **array;
public:
    Test(const int x, const int y){
        int i;
        this->array = new int*[x]; // first level pointer asignation
        for(i=0;i<x;i++){
            this->array[x] = new int[y]; // second level pointer asignation
        }
        // this->array = new int[x][y] does not work
        this->x = x;
        this->y = y;
    }
};

请参阅this

答案 1 :(得分:0)

你可能会碰到&#34;所有尺寸必须是常数,除了最左边的&#34;讨论了here

相反,请尝试以下方法:

class Test {
private:
        int x;
        int y;
        int** myArray;
public:

        Test(const int x, const int y) : x(x), y(y) {
                myArray = new int*[x];

                for (int firstDimension = 0; firstDimension < x; firstDimension++) {

                        myArray[firstDimension] = new int[y];

                        for (int secondDimension = 0; secondDimension < y; secondDimension++) {
                                myArray[firstDimension][secondDimension] = secondDimension;
                        }
                }
        }

        ~Test() {
                for(int i = 0; i < x; i++)
                        delete[] myArray[i];
                delete[] myArray;
        }
};