C++ 中的构造函数列表
constructor lists in c++
所以基本上,我有一个名为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 作为默认值,您应该清楚地将其指示为数组
相关文章:
- 一对向量构造函数:初始值设定项列表与显式构造
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 构造函数/函数声明参数列表中的统一初始化
- 在初始化列表之外手动调用基类的构造函数
- 采用初始值设定项列表的构造函数
- 提供初始值设定项列表构造函数的有效方法
- C 标准中是否有任何计划来解决初始化器列表构造函数的不一致性
- 接受迭代器的初始值设定项列表构造函数
- STD :: MAP初始化列表构造函数
- 如何避免丢失自动生成的初始化列表构造函数
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- 初始化列表构造函数错误带有CRTP
- 启用默认初始值设定项列表构造函数
- 使用初始化列表构造函数时C++奇怪的行为
- 自定义列表类的初始值设定项列表构造函数
- 初始值设定项列表构造函数导致右值构造函数不明确
- 调用初始化列表构造函数的不同方式
- 为什么std::array不包含初始化列表构造函数
- C++ 为类模板提供初始值设定项列表构造函数
- 何时使用初始值设定项列表构造函数