为什么我收到错误?重载运算符[]

时间:2013-07-23 06:11:49

标签: c++ windows visual-studio-2010 templates

当我尝试编写这样的代码时,我得到了这个编译错误。实际上,operator []过载了。 我很困惑,任何人都可以帮助我吗?

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;
    }

1 个答案:

答案 0 :(得分:2)

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

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

但你传递的论点是5,它是一个文字,因此是一个右值。

由于运算符的实现似乎没有修改键,我建议您更改声明,以便它采用const左值引用:

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

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