当我尝试写这样的代码,我得到这个编译错误。 实际上,运算符[]被超载。 我很困惑,有人可以帮我吗?
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; }
您的operator []被声明为一个非const的左值引用:
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 )
这可以绑定到一个右值,一切都会好的。