简体   繁体   English

来自另一个具有数组初始化功能的构造函数的C ++构造函数调用

[英]C++ constructor call from another constructor with array initialisation

I am writing a new class using OpenGL, i have two possibilities for my constructor : 我正在使用OpenGL编写新类,对于构造函数我有两种可能性:

VertexObject();
VertexObject(GLuint* vertices,GLuint* elements);

What i would like to do is that VertexObject() calls the other one with an already inisialised array such as 我想做的是VertexObject()调用另一个已经初始化的数组,例如

    VertexObject::VertexObject() : 
    VertexObject( 
    (GLuint[]) {
        0, 1, 2,
        2, 3, 0
    },
    (GLuint[]) {
        0, 1, 2,
        2, 3, 0
    }) {}

But it seems C++ won't let me do it, error being 'taking address of temporary array'. 但是似乎C ++不允许我这样做,错误是“获取临时数组的地址”。 I am not even sure what i am asking for is doable but any help will be greatly appreciated. 我什至不确定我要的是可行的,但是任何帮助将不胜感激。

I propose you to look at boost library, particularly assign pattern(facilitates initialization of containers) might help. 我建议您看一下Boost库,尤其是分配模式(有助于初始化容器)可能会有所帮助。

Here is a small code snippet that might give you grasp of idea: 这是一个小代码段,可能会让您了解主意:

VertexObjectc(boost::assign::list_of(0)(1)(2)(2)(3)(0).convert_to_container<GLuint>() );

I haven`t tested it. 我还没有测试。

If you deep copy the array in the constructor or if the arrays are never ever modified and VertexObject doesn't take the ownership of the pointers, this should work: 如果您在构造函数中深度复制该数组,或者从未修改过该数组并且VertexObject不获取指针的所有权,则这应该起作用:

GLuint def_vert[6] = { // static storage
    0, 1, 2,
    2, 3, 0
};
VertexObject::VertexObject() : 
VertexObject(def_vert, def_vert) {}

You can use separate arrays if you want different values for each parameter of course. 当然,如果每个参数都需要不同的值,则可以使用单独的数组。

Try this: 尝试这个:

// 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;
}

( http://ideone.com/IvujSq ) http://ideone.com/IvujSq

Note that it works on C++11. 请注意,它适用于C ++ 11。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM