我正在使用OpenGL编写一个新类,我的构造函数有两种可能性:
VertexObject();
VertexObject(GLuint* vertices,GLuint* elements);
我想要做的是VertexObject()使用已经被inisialised的数组调用另一个,例如
VertexObject::VertexObject() :
VertexObject(
(GLuint[]) {
0, 1, 2,
2, 3, 0
},
(GLuint[]) {
0, 1, 2,
2, 3, 0
}) {}
但似乎C ++不会让我这样做,错误是'获取临时数组的地址'。 我甚至不确定我要求的是可行的,但任何帮助将不胜感激。
答案 0 :(得分:2)
我建议您查看 boost 库,特别是分配模式(便于容器初始化)可能有所帮助。
这是一个小代码片段,可能会让您掌握一些想法:
VertexObjectc(boost::assign::list_of(0)(1)(2)(2)(3)(0).convert_to_container<GLuint>() );
我没有测试过它。
答案 1 :(得分:1)
如果你在构造函数中深度复制数组,或者数组永远不会被修改而且VertexObject
没有取得指针的所有权,那么这应该有效:
GLuint def_vert[6] = { // static storage
0, 1, 2,
2, 3, 0
};
VertexObject::VertexObject() :
VertexObject(def_vert, def_vert) {}
如果您希望每个参数的值都不同,则可以使用单独的数组。
答案 2 :(得分:0)
试试这个:
// VertexObject.h
class VertexObject
{
private:
static const GLuint m_default_vertices[6], m_default_elements[6];
static GLuint *GetDefVertices();
static GLuint *GetDefElements();
public:
VertexObject() : VertexObject(GetDefVertices(), GetDefElements()) { }
...
};
// VertexObject.cpp
const GLuint VertexObject::m_default_vertices[6] = {
0, 1, 2,
2, 3, 0
};
const GLuint VertexObject::m_default_elements[6] = {
0, 1, 2,
2, 3, 0
};
GLuint *VertexObject::GetDefVertices()
{
static thread_local GLuint ar[6];
memcpy(ar, m_default_vertices, sizeof(ar));
return ar;
}
GLuint *VertexObject::GetDefElements()
{
static thread_local GLuint ar[6];
memcpy(ar, m_default_elements, sizeof(ar));
return ar;
}
请注意,它适用于C ++ 11。