使用重载运算符 [] 更改结构的值

vla*_*_sl 0 c++ class data-structures

我正在尝试制作自定义矢量数据结构。它将始终包含 4 个浮点值。我想通过它的属性名称访问它,但也可以通过运算符 [] 访问它,因此它也可以使用索引访问,例如数组。它应该可以通过运算符 [] 进行编辑,例如向量或数组。到目前为止,我已经这样做了:

struct vec4
{
    float* x;
    float* y;
    float* z;
    float* w;

    vec4() : data(4, 0.0f) { Init(); }
    vec4(float x, float y, float z, float w)
    {
        data = std::vector<float>{ x, y, z, w };
        Init();
    }

    float* operator[](int i) const
    {
        switch (i)
        {
        case 0: return x;
        case 1: return y;
        case 2: return z;
        case 3: return w;
        default: __debugbreak();
        }
    }

private:
    std::vector<float> data;

    void Init()
    {
        std::vector<float>::iterator start = data.begin();

        this->x = &(*++start);
        this->y = &(*++start);
        this->z = &(*++start);
        this->w = &(*start);
    }
};
Run Code Online (Sandbox Code Playgroud)

有没有更优雅的方法来解决这个问题?

Nat*_*ica 5

拥有单独的成员,然后使用 switch 语句几乎是做到这一点的方法。虽然你不需要向量,但可以像这样编写类

struct vec4
{
    float x = 0;
    float y = 0;
    float z = 0;
    float w = 0;

    vec4() = default;
    vec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {}

    const float& operator[](int i) const
    {
        switch (i)
        {
        case 0: return x;
        case 1: return y;
        case 2: return z;
        case 3: return w;
        default: __debugbreak();
        }
    }
    
    float& operator[](int i)
    {
        // this is safe because we are in a non-const function, so this cant point to a const object
        return const_cast<float&>(static_cast<const vec4&>(*this)[i]);
    }
};
Run Code Online (Sandbox Code Playgroud)