【问题标题】:const and overloading operatorconst 和重载运算符
【发布时间】: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&amp; key) 为什么&amp; 在这里?

标签: c++ operator-overloading subscript-operator


【解决方案1】:

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

const 版本无效,因为map5const

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

要么从const 版本的KeyType 参数中删除&amp;,要么将该参数设为const

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 2015-03-29
    • 2014-07-28
    • 1970-01-01
    • 2016-11-05
    • 2020-11-08
    • 1970-01-01
    相关资源
    最近更新 更多