为什么我会出错?运算符[]过载



当我尝试写这样的代码时,我会遇到编译错误。实际上,运算符[]已过载。我很困惑,有人能帮我吗?

AssocArray<int, int> ary;
ary.addItem(1, 1);
ary.addItem(2, 1);
ary.addItem(3, 1);
ary.addItem(4, 1);
ary.addItem(5, 1);
ary[5] = 2;//error occur here

以下是错误消息:

error C2679: binary '[' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
...could be 'int &opt::AssocArray<key,value>::operator [](key &)'
with
[
    key=int,
    value=int
]
while trying to match the argument list '(opt::AssocArray<key,value>, int)'
with
[
    key=int,
    value=int
]

AssocArray的实现如下(注意:它位于*.h文件中):

    template <typename key, typename value>
    class AssocArray
    {
    public:
        typedef typename std::pair<key, value> type;
        bool addItem(key& k, value& v);
        bool addItem(key k, value v);
        bool isItem(key& k);
        value& operator[] (key& k);
        typename std::vector<type>::iterator begin()
        {
            return vecData.begin();
        }
        typename std::vector<type>::iterator end()
        {
            return vecData.end();
        }
    protected:
    private:
        std::vector<type> vecData;
    };
    template <typename key, typename value>
    bool AssocArray<key, value>::addItem( key k, value v )
    {
        if(isItem(k)) return false;
        vecData.push_back(std::make_pair(k, v));
        return true;
    }
    template <typename key, typename value>
    value& AssocArray<key, value>::operator[]( key& k )
    {
        auto iter = std::find_if(vecData.begin(), vecData.end(),
            [&](type& param)
        {
            return param.first == k;
        }
        );
        if(vecData.end() != iter)
            return iter->second;
        value v;
        vecData.push_back(std::make_pair(k, v));
        return vecData.rbegin()->second;
    }
    template <typename key, typename value>
    bool AssocArray<key, value>::isItem( key& k )
    {
        auto iter = std::find_if(vecData.begin(), vecData.end(),
            [&](type& param) mutable -> bool
        {
            return param.first == k;
        }
        );
        return vecData.end() != iter;
    }

您的运算符[]被声明为采用非常量左值引用:

template <typename key, typename value>
value& AssocArray<key, value>::operator[]( key& k )

但是您传递的参数是5,它是一个文字,因此是一个右值。

由于运算符的实现似乎不会修改键,我建议您更改声明,使其采用常量左值引用:

template <typename key, typename value>
value& AssocArray<key, value>::operator[]( const key& k )

这可以绑定到一个右值,一切都会好起来的。

相关内容

  • 没有找到相关文章

最新更新