【发布时间】:2016-01-16 10:30:02
【问题描述】:
我有通用地图对象。
我想重载 operator[] 所以map[key] 返回键的值。
我做了两个版本的下标运算符。
非常量:
ValueType& operator[](KeyType key){
常量:
const ValueType& operator[]( KeyType& key) const{
非常量版本可以正常工作,但是当我创建 const Map 时出现问题。 我主要写:
const IntMap map5(17);
map5[8];
我收到以下错误:
ambiguous overload for 'operator[]' (operand types are 'const IntMap {aka const mtm::MtmMap<int, int>}' and 'int')
invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
【问题讨论】:
-
operator[]( KeyType& key)为什么&在这里?
标签: c++ operator-overloading subscript-operator