加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 下标(“[]”)运算符给出了奇怪的错误

发布时间:2020-12-16 09:21:00 所属栏目:百科 来源:网络整理
导读:我从visual studio获得了一些奇怪的行为,关于以下代码片段,错误列表显示了E0349的几个实例:没有运算符“[]”匹配这些操作数. Intellisense似乎暗示了类型不匹配,但正如您将在代码中看到的那样,没有类型不匹配. 首先,我为了制作mat4而定义了一个Vec4结构: (
我从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类,我创建了一个4×4矩阵:

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 []是一个非const成员函数,不能在Mat4f :: Mat4f的参数m上调用,它被声明为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];
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读