C++ 常量与重载运算符

C++ 常量与重载运算符,c++,operator-overloading,subscript-operator,C++,Operator Overloading,Subscript Operator,我有一个通用的映射对象。 我想重载操作符[],以便map[key]返回键的值。 我制作了两个版本的下标操作符 非常量: ValueType& operator[](KeyType key){ 常数: const ValueType& operator[]( KeyType& key) const{ 非常量版本工作正常,但当我创建常量映射时,我遇到了问题。 我主要写: const IntMap map5(17); map5[8]; 我得到了这些

我有一个通用的映射对象。 我想重载操作符[],以便
map[key]
返回键的值。 我制作了两个版本的下标操作符

非常量:

ValueType& operator[](KeyType key){
常数:

const ValueType& operator[]( KeyType&   key) const{
非常量版本工作正常,但当我创建常量映射时,我遇到了问题。 我主要写:

     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'   
运算符[]的不明确重载(操作数类型为“const IntMap{aka const mtm::MtmMap}”和“int”)
从“int”类型的右值初始化“int&”类型的非常量引用无效

关于歧义的错误消息反映了编译器将两个
运算符[]()
视为匹配
map5[8]
的可能候选项。两位候选人都一样好(或坏,取决于你如何看待它)

const
版本无效,因为
map5
const

const
版本要求使用无效的右值(文本
8
)初始化对
KeyType
的非
const
引用。从错误消息中,您的
KeyType
int

const
版本的
KeyType
参数中删除
&
,或者在此处设置该参数
const

运算符[](KeyType&key)
为什么
&