C++ 中的构造函数列表

constructor lists in c++

本文关键字:列表 构造函数 C++      更新时间:2023-10-16

所以基本上,我有一个名为vertex2的类。这是我为更容易使用OpenGL而制作的一个类(对我来说(。所以我做了一个构造函数。它拿了一个浮动列表。但问题来了。我试图创建一个浮点数列表的变量;它float list[] = {1, 0, 0, 1, 1, 1, 0} 我分配了一个顶点2,它起作用了。但是我尝试粘贴它:{1, 0, 0, 1, 1, 1, 0}初始化,但它不起作用。

struct vertex2
{
    vertex2(float *vertices);
private:
    float *m_vertices;
public:
    float *ConvertToFloatArray();
};
static game::data::vertex2 vertices = { -0.5f, -0.5f,
    0.5f, -0.5f,
    0.5f, 0.5f,
    -0.5f, 0.5f };

但是如果我这样做:

static float verts[] = { -0.5f, -0.5f,
    0.5f, -0.5f,
    0.5f, 0.5f,
    -0.5f, 0.5f };
static game::data::vertex2 vertices = verts;

它以某种方式起作用。

当你在做:

struct vertex2
{
    vertex2(float *vertices);
private:
    float *m_vertices;
public:
    float *ConvertToFloatArray();
};
static float verts[] = { -0.5f, -0.5f,
    0.5f, -0.5f,
    0.5f, 0.5f,
    -0.5f, 0.5f };
static game::data::vertex2 vertices = verts;

正在声明一个带有顶点的静态变量,并在构造函数上传递指向它的指针,并且(我的猜测,因为您没有包含完整的代码(将指针保存在您的对象中。如果有人修改了顶点,则类上的顶点将被修改(同样,如果您修改类上的顶点,它将修改顶点变量(。

但是当你这样做时:

static game::data::vertex2 vertices = { -0.5f, -0.5f,
    0.5f, -0.5f,
    0.5f, 0.5f,
    -0.5f, 0.5f };

您传递的是浮点数列表,而不是指针。

相反,我建议你玩这个:https://ideone.com/GVvL8y

#include <array>
class vertex2 // use class whenever possible, not struct
{
public:
    static const int NUM_VERTICES= 6;
public:
    // Now you can only init it with a reference to a 6 float array
    // If you use float* you'll never know how many floats are there
    constexpr vertex2(float (&v)[NUM_VERTICES])
    : vertices{v[0], v[1], v[2], v[3], v[4], v[5]}
    {
    }
    // Will take a list of numbers; if there's more than 6
    // will ignore them. If there's less than 6, will complete
    // with 0
    constexpr vertex2(std::initializer_list<float> list)
    {
        int i= 0;
        for (auto f= list.begin(); i < 6 && f != list.end(); ++f) {
            vertices[i++]= *f;
        }
        while (i < NUM_VERTICES) {
            vertices[i++]= 0;
        }
    }
    constexpr vertex2() = default;
    constexpr vertex2(vertex2&&) = default;
    constexpr vertex2(const vertex2&) = default;
    float* ConvertToFloatArray() const;
    // Just for debugging
    friend std::ostream& operator<<(std::ostream& stream, const vertex2& v)
    {
        stream << '{' << v.vertices[0];
        for (int i= 1; i < vertex2::NUM_VERTICES; i++) {
            stream << ',' << v.vertices[i];
        }
        return stream << '}';
    }
private:
    std::array<float, NUM_VERTICES> vertices{};
};

像这样制作

vertex2 vertices{(float []){-0.5f, -0.5f,
        0.5f, -0.5f,
        0.5f, 0.5f,
        -0.5f, 0.5f }};

编译器尝试使用 initializer_list 作为默认值,您应该清楚地将其指示为数组