[英]C++ constructor call from another constructor with array initialisation
我正在使用OpenGL編寫新類,對於構造函數我有兩種可能性:
VertexObject();
VertexObject(GLuint* vertices,GLuint* elements);
我想做的是VertexObject()調用另一個已經初始化的數組,例如
VertexObject::VertexObject() :
VertexObject(
(GLuint[]) {
0, 1, 2,
2, 3, 0
},
(GLuint[]) {
0, 1, 2,
2, 3, 0
}) {}
但是似乎C ++不允許我這樣做,錯誤是“獲取臨時數組的地址”。 我什至不確定我要的是可行的,但是任何幫助將不勝感激。
我建議您看一下Boost庫,尤其是分配模式(有助於初始化容器)可能會有所幫助。
這是一個小代碼段,可能會讓您了解主意:
VertexObjectc(boost::assign::list_of(0)(1)(2)(2)(3)(0).convert_to_container<GLuint>() );
我還沒有測試。
如果您在構造函數中深度復制該數組,或者從未修改過該數組並且VertexObject
不獲取指針的所有權,則這應該起作用:
GLuint def_vert[6] = { // static storage
0, 1, 2,
2, 3, 0
};
VertexObject::VertexObject() :
VertexObject(def_vert, def_vert) {}
當然,如果每個參數都需要不同的值,則可以使用單獨的數組。
嘗試這個:
// 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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.