微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用重载运算符 [] 更改结构的值

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

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

解决方法

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

一样编写类
books_xmls
 Year\...
     Month\...
        Day\...
              books
,

怎么样

struct vec4
{
    vec4() : vec4(0,0) {}
    vec4(float x,float y,float z,float w) : data{ x,y,z,w } {}

    float operator[](int i) const { return data[i]; }
    float& operator[](int i) { return data[i]; }
    float at(int i) const { return data.at(i); }
    float& at(int i) { return data.at(i); }

    float x() const { return data[0]; }
    float y() const { return data[1]; }
    float z() const { return data[2]; }
    float w() const { return data[3]; }

    float& x() { return data[0]; }
    float& y() { return data[1]; }
    float& z() { return data[2]; }
    float& w() { return data[3]; }

private:
    std::array<float,4> data;
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。