所以基本上,我有一个叫做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;
它以某种方式起作用。
答案 0 :(得分:3)
在做的时候:
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;
您正在使用顶点声明一个静态变量,并在构造函数上传递一个指向它的指针,(我的猜测,因为您没有包括完整的代码),保存了指针< / strong>。如果有人修改了顶点,则该类上的顶点将被修改(同样,如果您修改了该类上的顶点,则它将修改vertices变量)。
但是当您这样做时:
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{};
};
答案 1 :(得分:-2)
像这样
vertex2 vertices{(float []){-0.5f, -0.5f,
0.5f, -0.5f,
0.5f, 0.5f,
-0.5f, 0.5f }};
编译器尝试默认使用initializer_list,您应该清楚地将其表示为数组