我在将我的 std::vector 交给另一个类(class)时遇到问题。我将数据放入 std::vector 并将其放入名为“Mesh”的类中。而“网格”变成了“模型”。
// Store the vertices
std::vector<float> positionVertices;
positionVertices.push_back(-0.5f);
positionVertices.push_back(-0.5f);
positionVertices.push_back( 0.5f);
positionVertices.push_back(-0.5f);
positionVertices.push_back(-0.5f);
positionVertices.push_back( 0.5f);
// Put them into a mesh and the mesh into a model
Mesh mesh = Mesh(positionVertices);
Model model = Model(mesh);
在模型类中,我取回网格的位置顶点并将其转换为 float[]。但似乎是这样,我分配 std::vector 的方式是错误的,因为在检查模型类中的 std::vector 时,它的大小为 0。
// Store the vertices
float* dataPtr = &data[0];
glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(float), dataPtr, GL_STATIC_DRAW);
如何将数据正确地导入其他类?
我也不确定网格类的构造函数的工作方式。 网格.h:
// Mesh.h
class Mesh
{
public:
std::vector<float> positionVertices;
Mesh(std::vector<float>);
~Mesh();
};
网格.cpp:
// Mesh.cpp
Mesh::Mesh(std::vector<float> positionVertices) : positionVertices(Mesh::positionVertices)
{
}
模型.h:
// Model.h
class Model
{
public:
Mesh mesh;
unsigned int vertexArray;
unsigned int vertexCount;
Model(Mesh);
~Model();
void storeData(std::vector<float> data, const unsigned int index, const unsigned int size);
};
模型.cpp:
// Model.cpp
Model::Model(Mesh mesh) : mesh(Model::mesh)
{ ... }
最佳答案
// Mesh.cpp
Mesh::Mesh(std::vector<float> positionVertices) :
positionVertices(Mesh::positionVertices) // Here's the problem
{
}
初始化列表中的 positionVertices
是 Mesh::positionVertices
,因此您将其分配给自身。
使用
positionVertices(positionVertices)
另外,改变
Mesh::Mesh(std::vector<float> positionVertices) :
到
Mesh::Mesh(const std::vector<float>& positionVertices) :
所以您不会制作不必要的载体拷贝。
关于c++ - std::vector 的正确分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55290328/