Normally I would define a new array and vector with size n in C++ like this:
int* xArray = new int[n];
vector<int> yVector(n);
But now I have a class Maze which has a header. The arrays and vectors are supposed to be declared in the header and then allocated in f.ex. the constructor.
The arrays are declared in Maze.h like this:
class Maze {
public:
int* xArray;
}
And then allocated in Maze.cpp like this:
xArray = new int[n];
Now I can use xArray from any function in the class Maze.
But what is the equivalent way to declare and allocate vectors? This is what I tried:
In Maze.h:
class Maze {
public:
vector<int> yVector;
}
In Maze.cpp:
yArray(n);
But when compiling I get:
error: no match for call to ‘(std::vector<int>) (int)’
yVector(n);
So does it think that yVector is a function, and that I am trying to call the function? I tried to specify that this is a class field by writing this->yArray(n);
instead, but that made no difference.
Next I tried putting vector<int> yArray(n);
in the constructor. It compiles. But when I later try to use yVector[0]
in another function I get Segmentation fault (core dumped)
, so I guess all I did was declare a new, local vector, which is not what I wanted.
So how am I supposed to define class vectors when using a header file?
Aucun commentaire:
Enregistrer un commentaire