对于以下代码段,我从Visual Studio中得到了一些奇怪的行为,错误列表显示了E0349的多个实例:没有运算符“[]”与这些操作数匹配。

Intellisense似乎暗示类型不匹配,但是正如您将在代码中看到的那样,没有类型不匹配。

首先,我为了制作mat4定义了Vec4结构:
(我只包含了相关功能)

struct Vec4f
{
    union
    {
        struct { float x, y, z, w; };
        struct { float r, g, b, a; };
    };
    // copy constructor
    Vec4f(Vec4f const & v) :
        x(v.x),
        y(v.y),
        z(v.z),
        w(v.w)
    {

    }
    // Operators
    float & operator[](int index)
    {
        assert(index > -1 && index < 4);
        return (&x)[index];
    }

    Vec4f & operator=(Vec4f const & v)
    {
        // If I use: "this->x = v[0];" as above, E0349
        this->x = v.x;
        this->y = v.y;
        this->z = v.z;
        this->w = v.w;
        return *this;
    }
}

使用上面的Vec4类,我创建了一个4x4矩阵:
struct Mat4f
{
    //storage for matrix values
    Vec4f value[4];

    //copy constructor
    Mat4f(const Mat4f& m)
    {
        value[0] = m[0]; // calling m[0] causes E0349
        value[1] = m[1];
        value[2] = m[2];
        value[2] = m[3];
    }

    inline Vec4f & operator[](const int index)
    {
        assert(index > -1 && index < 4);
        return this->value[index];
    }
}

当调用任何“[]”运算符时,我最终遇到此E0349错误,并且我不理解该问题。奇怪的是,文件编译就很好了。我已尝试按照对另一个问题的答案中的建议删除隐藏的“.suo”文件,但无济于事。我很乐意向我解释这一点。

最佳答案

Mat4f::operator[]是一个非常量成员函数,不能在m的参数Mat4f::Mat4f上调用,它被声明为const & Mat4f

您可以添加另一个const重载,可以在常量上调用它。例如

inline Vec4f const & operator[](const int index) const
//           ~~~~~                               ~~~~~
{
    assert(-1 < index && index < 4); // As @Someprogrammerdude commented, assert(-1 < index < 4) doesn't do what you expect
    return this->value[index];
}

09-06 09:13