提问者:小点点

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


我正在尝试制作一个自定义的矢量数据结构。它将始终包含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);
    }
};

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


共1个答案

匿名用户

拥有单独的成员,然后使用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]);
    }
};