I want to make vertices an array of Vector. But I don’t know how to declare and initialize it. I tried this, but it complains:
class Mesh {
public:
Vector vertices[];
int verticesCount;
Mesh();
virtual ~Mesh();
};
Mesh::Mesh() {
verticesCount = 4;
vertices = new Vector[verticesCount]; // error: expected primary-expression before ']' token
vertices[0] = new Vector(0, 0, 0);
vertices[1] = new Vector(1, 0, 0);
vertices[2] = new Vector(1, 1, 0);
vertices[3] = new Vector(0, 1, 0);
}
Mesh::~Mesh() {
delete vertices;
}
Edit
Trying to correct, applying your tips, I reach this:
Vector* vertices;
//...
vertices = new Vector[verticesCount];
vertices[0] = Vector(0, 0, 0);
vertices[1] = Vector(1, 0, 0);
vertices[2] = Vector(1, 1, 0);
vertices[3] = Vector(0, 1, 0);
//...
delete[] vertices;
And it worked. But is it ok?
You declare
verticesas an unspecified array ofVector, then you try to allocate memory for each entry in the array.First C++ doesn’t support empty arrays (if I remember correct), and the data type of the array is not pointers to
Vectorwhich means you can not use thenewexpressions.If you want to use a dynamic array of vectors, please use
std::vectorinstead:And in the constructor: