c++ - 将类转换为固定长度的 float 组

标签 c++

如何将以下类转换为固定长度的 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;
}

Live Demo

std::array与使用 C 风格的数组一样高效,没有性能损失。您也可以改用 std::vector

即使在 C 中也不能只返回和复制一个数组。这就是为什么如果你绝对想使用 C 数组,你必须有一个像 fillArray 这样的函数。

关于c++ - 将类转换为固定长度的 float 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37413497/

相关文章:

c++ - `std::filesystem::path` 没有标准哈希值吗?

c++使用 boost 测试

c++ - 在 C++ 中使用友元类和模板时出现超出范围错误

C++ 语法 - 条件运算符和算术运算符的组合

java - 从 Java 调用 C++ 函数

C++。 std::condition_variable 和多个等待线程

使用 std::thread 的 C++ 多线程应用程序在 Windows 上运行良好,但在 Ubuntu 上运行不正常

c++ - 会不会在做递归内存的时候声明一个全局变量更高效更快?

c++ - 使用 C++ 进行图像处理还是继续使用 OpenCV?

c++ - 如何读取高度图值以生成地形?