c++ - std::vector 的正确分配

标签 c++ opengl

我在将我的 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/

相关文章:

c++ - 包含的库仍然导致 "undefined reference"错误

c++ - 请求 'print'中的成员 'y',非类类型

opengl - glRotatef 无法正常工作

c++ - SFML 中的 OpenGL 累积缓冲区?

java - JOGL Opengl WriteCloneable 在 Eclipse 中

c++ - 资源而不是外部文件 C++

C++ Typedef to const value 指针的常量地址

c++ - 所有进程句柄都相同(CreateToolhelp32Snapshot)

docker - 在 docker 中使用 OpenGL 和 nvidia-docker2

qt - 运行 QML 应用程序时,Qt 5.6 中列入黑名单的显卡会发生什么情况?