【问题标题】:How to provide const read-only access to a wrapper class如何提供对包装类的 const 只读访问
【发布时间】:2015-04-09 23:17:44
【问题描述】:

我有以下程序。我想要完成的是创建一个对 unordered_map 上的可变包装器的常量引用,我可以传递它以进行只读查找。但是,由于 operator[] 重载,我无法编译以下代码。

从这段代码中,有人知道我做错了什么吗?

#include <unordered_map>
#include <string>

using std::unordered_map;
using std::string;

class M {
private:
    unordered_map<string, string> m;

public:
    string const& operator[](string const& s) const {
        return m[s]; // line 13
    }

    string& operator[](string const& s) {
        return m[s];
    }
};

int main() {
    M m;

    m[string("a")] = string("answer_a");

    M const& m1 = m;
    string const& test = m1[string("a")];

    return 0;
}

错误(第 13 行)是

错误:传递 'const std::unordered_map, std::basic_string >' 作为 'this' 参数 'std::__detail::_Map_base<_key _pair std::_select1st>, true, _Hashtable>::mapped_type& std::__detail::_Map_base<_key _pair std::_select1st>, true, _Hashtable>::operator[](const _Key&) [与 _Key = std::basic_string, _Pair = std::pair, std::basic_string >, _Hashtable = std::_Hashtable, std::pair, std::basic_string >, 标准::分配器, std::basic_string > >, std::_Select1st, std::basic_string > >, std::equal_to >, 标准::哈希>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy,假,假,真>, std::__detail::_Map_base<_key _pair std::_select1st>, true, _Hashtable>::mapped_type = std::basic_string]' 丢弃限定符 [-fpermissive]

【问题讨论】:

  • 您做错了什么是没有阅读文档以了解 operator[] 对地图的作用。
  • 我不会拒绝这个问题,这是一个公平的问题,我很确定我们所有人之前都犯过这样的错误。尤其是当stackoverflow.com/q/1642028/3093378 是 SO 上投票次数第三多的问题时。

标签: c++ c++11


【解决方案1】:

unordered_map 运算符[] 是非常量的,因为它在映射键还不存在时添加它。相反,您应该使用

return m.at(s);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多