如何将以下类转换为固定长度的 float 数组?
class Vertex
{
public:
Vertex( float x = 0,
float y = 0,
float z = 0)
: x(x), y(y), z(z) {}
float x, y, z;
};
例如,我想这样使用它:
Vertex v(0, 1, 0);
float arr[3] = v; // How to convert here?
谢谢!
编辑:
我应该在发布这个问题之前添加一些背景信息。
我使用 C 风格数组的原因是因为我想将高级顶点对象组合成一个顶点数组以便用 OpenGL 渲染,据我所知这需要一个集合原始数组 (float[3]
) 或结构。
为此,我认为 user2079303's answer是最好的选择。但是,如果存在更优雅的解决方案,那就更好了。 :)
最佳答案
#include <iostream>
#include <array>
using namespace std;
class Vertex
{
public:
Vertex( float x = 0,
float y = 0,
float z = 0)
: x(x), y(y), z(z) {}
operator array<float, 3>() const {
return {x,y,z};
}
/* See @user2079303's answer for a compile-time check of the array dimension */
void fillArray(float arr[3]) {
arr[0] = x;
arr[1] = y;
arr[2] = z;
}
float x, y, z;
};
int main() {
Vertex v(1,1.4,2);
array<float, 3> arr = v;
float arr2[3];
v.fillArray(arr2);
for (int i = 0; i < 3; i++) {
cout << arr[i] << " " << arr2[i] << endl;
}
return 0;
}
std::array与使用 C 风格的数组一样高效,没有性能损失。您也可以改用 std::vector
。
即使在 C 中也不能只返回和复制一个数组。这就是为什么如果你绝对想使用 C 数组,你必须有一个像 fillArray
这样的函数。
关于c++ - 将类转换为固定长度的 float 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37413497/