2014-12-23 2 views
0

Я пытаюсь сделать следующее:Создание 2D-массив внутри constuctor в C++

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-массив, в то время как оценки будут даны в конструкторе. Как я могу это достичь?

Он работает с обычным массивом:

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

Смотрите этот пост: http://stackoverflow.com/questions/8294102/proper-way-to-declare-a-variable-length-two-dimensional- array-in-c –

+4

использовать 'std :: vector ' вместо необработанных указателей – vsoftco

+0

Можете ли вы использовать шаблоны? Ваш пример будет протекать, если вы забудете добавить деструктор, освобождающий массив. – Kimi

ответ

0

Возможно, вы столкнулись с проблемой «Все измерения должны быть константами, кроме самого левого», обсуждаемыми 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; 
     } 
}; 
+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.

Смежные вопросы