下面是我正在尝试做的事情的简化版本。
我在
getMove2()
的返回线上收到 C2678 错误。 getMove()
和 getMove2()
之间的唯一区别是 const
.
我有一个解决方法(注释掉的行),但我试图理解为什么该行不起作用,以及如何修复它。
#include <string>
#include <map>
class Dummy
{
public:
Dummy(std::string character, int a, int b, int c) {
name = character;
moves["a"] = a;
moves["b"] = b;
moves["c"] = c;
}
int getMove(std::string move_name) {
return moves[move_name];
}
int getMove2(std::string move_name) const {
return moves[move_name];
//return moves.find(move_name)->second; //This works but I can't figure out how to make the above work
}
private:
std::string name;
std::map <std::string, int> moves;
};
我尝试过将
map
的不同部分作为 const
,但没有运气。
类模板
std::map
声明了以下方法来按键访问单个元素:
T& operator[](key_type&& x);
T& operator[](key_type&& x);
T& at(const key_type& x);
const T& at(const key_type& x) const;
如您所见,两个下标运算符都没有声明为
const
方法,因此您不能在 const
std::map
对象上调用它们。由于 getMove2()
被声明为 const
,它的 this
指针具有 Dummy const *
类型,因此当通过该指针访问时,moves
成员是 const
。
但是,您可以调用声明为
map::at()
的const
方法。
例如:
int getMove2(std::string move_name) const {
return moves.at( move_name );
}