简体   繁体   中英

Initialising unknown ranged array in class C++

I've got a beginner's problem:

class Snake
{
public:
    int mapa[][];
    Snake(int szer,int wys)
    {
        mapa[szer][wys];
    }
};

I'm trying to do something like above(create array with size defined in the constructor), but it seams to be not possible in C++. Is there any way to do this work?

是:

std::vector<std::vector<int> > ...;

Depending on you needs you can either use a std::vector<std::vector<T> > or a class giving a std::vector<T> an interface of a two dimensional areay. For tha latter you would overload operator[]() to return an object giving a subrange of the internal std::vector<T> the felling of an array itself. If you just want to use the subscriot operator, returning a std::vector<T>::iterator would work but it wouldn't expose, eg, begin() and end() iterators.

If you really want to use the new keyword, you would have to do a 2-step initialization:

int **mapa;
Snake(int szer,int wys)
{
    mapa = new int*[szer];
    for (int i = 0; i < szer; i ++)
        mapa[i] = new int[wys];
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM