常量和重载运算符

const and overloading operator

本文关键字:运算符 重载 常量      更新时间:2023-10-16

我有通用的地图对象。我想重载运算符 [],以便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'   

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

const版本无效,因为map5 const

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

const版本的KeyType参数中删除&,或将该参数设为const