首页 > 解决方案 > C++中的构造函数列表

问题描述

所以基本上,我有一个名为 vertex2 的类。这是我为更容易(对我而言)使用 OpenGL 而做的一门课。所以我做了一个构造函数。它接受了一个浮动列表。但这就是问题所在。我试图创建一个浮动列表的变量;它是float list[] = {1, 0, 0, 1, 1, 1, 0}并且我分配了一个 vertex2 并且它起作用了。但我尝试粘贴:{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;

它以某种方式起作用。

标签: c++constructor

解决方案


当你在做:

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

推荐阅读