There is such a class:

class Field { public: Field(sf::Vector2<int> size); ~Field(); sf::Vector2<int> size; bool* tileState; private: }; Field::Field(sf::Vector2<int> size) { this->size = size; this->tileState = new bool[this->size.x][this->size.y]{}; } Field::~Field() { //пока удалять не буду } 

The problem is that I can not select a two-dimensional array in the constructor but more than anything, what's the problem?

    2 answers 2

    Because in C ++ there are no two-dimensional arrays, instead of them - arrays of arrays (that is, the field type is bool** ). Accordingly, you must first allocate memory for one dimension, then for another:

     this->tileState = new bool*[this->size.x]; for (int i=0; i < this->size.x; ++i) this->tileState[i] = new bool[this->size.y]; 

    You need to clear the memory in the same way, in the reverse order.

    • There are no two-dimensional arrays anywhere, it’s just an abstraction like this - AR Hovsepyan
    • @ARHovsepyan, we are talking about syntactic constructs of the language. - free_ze
    • @ free_ze, and I say that not only in C ++ ... - AR Hovsepyan

    NxM array.

    Often they do it like this:

     type ** array = new type*[N]; for(size_t i = 0; i < N; ++i) array[i] = new type[M]; 

    Another option -

     type * array = new type[N*M]; 

    But then you need to remember that instead of array[i][j] you need to write array[i*M+j] .

    But the simplest is vector vectors:

     vector<vector<type>>array(N,vector<type>(M)); 

    You can, of course, dynamically ... but since this is done in the constructor, then there is no point.

     class Type { vector<vector<type>> array; ... Type(int N, int M):array(N,vector<type>(M)){} 

    Like that. And in the class itself, then there is a very simple treatment - array[i][j] without dereferencing.

    If the sizes are known at compile time, you can think about using array<type> .

    • But is it so bad? new bool[this->size.x]{ new bool[this->size.y]{} }; - ishidex2 pm
    • And so it will not work at all. - Harry
    • I get it - ishidex2
    • You compile , but it does not work ... Try to work with it. - Harry
    • The problem is that the dimensions are unknown - ishidex2