通过访问器函数使用重载的operator [] [英] Using overloaded operator[] via an accessor function
问题描述
我有一个访问器函数,返回一个类型的引用(std :: map)... ...
I have an accessor function that returns a const reference to a type (std::map) ... ...
myMap_t const& getMap() const {return paramMap;}
类型具有重载 ]
运算符。然后使用 []
运算符直接从getter函数中以下面的方式,但实际上是工作的语法。
The type has an overloaded []
operator. What is the syntax to then use the []
operator directly from the getter function in a way like the following, but that actually works.
parameter = contextObj.getMap()[key];
错误讯息是:
context.cpp:35: error: passing
'const std::map<
std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
float,
std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >,
std::allocator<std::pair<
const std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
float> > >'
as 'this' argument of
'_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&)
with
_Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
_Tp = float,
_Compare = std::less<std::basic_string<char, std::char_traits<char>, td::allocator<char> > >,
_Alloc = std::allocator<std::pair<
const std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
float> >]'
discards qualifiers
推荐答案
问题是在地图中的 operator []
是一个变异操作,你不能在对地图的const引用上调用它。它是变异的原因是它必须返回一个值的引用,并且为此,如果键在容器中不存在,它将插入一个新的默认构造值由该键并返回它的引用。
The problem is that operator[]
in a map is a mutating operation, and you cannot call it on a const reference to a map. The reason that it is mutating is that it must return a reference to a value, and for that, if the key was not already present in the container, it will insert a new default constructed value addressed by that key and return the reference to it.
如果你有一个const引用,并且你想确定一个元素是否存在(或访问它),你必须使用 std: :map<> :: find
,它将返回一个迭代器。如果元素不存在,迭代器的值为 m.end()
If you have a const reference, and you want to determine whether an element is present (or access it), you must use std::map<>::find
that will return an iterator. If the element is not present the value of the iterator would be m.end()
这篇关于通过访问器函数使用重载的operator []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!