【发布时间】:2023-03-21 23:14:02
【问题描述】:
我正在尝试使用以下struct 作为std::map 的自定义键:
struct ActionId {
// ENCAPSULATED MEMBERS
private:
size_t _id;
static size_t _root;
static size_t incrementedRoot() {
return (_root += 1);
}
// INTERFACE
public:
ActionId() :
_id(incrementedRoot()) { }
ActionId(const ActionId& that) :
_id(that._id) { }
ActionId& operator=(const ActionId& that) {
this->_id = that._id;
return *this;
}
bool operator==(const ActionId& that) const {
return this->_id == that._id;
}
bool operator!=(const ActionId& that) const {
return this->_id != that._id;
}
bool operator<(const ActionId& that) const {
return this->_id < that._id;
}
};
以下字典是单独的InputManager 类的成员:
std::map<ActionId, std::set<sf::Keyboard::Key>> _keyBindings;
在此成员函数中访问:
std::set<sf::Keyboard::Key> InputManager::keysBoundTo(ActionId action) const {
return _keyBindings[action];
}
不幸的是,该函数抛出此编译器错误:
错误 C2678: 二进制 '[' : 未找到采用 '
const std::map<Game2D::ActionId,std::set<sf::Keyboard::Key,std::less<_Kty>,std::allocator<_Kty>>,std::less<Game2D::ActionId>,std::allocator<std::pair<const Game2D::ActionId,_Ty>>>' 类型的左侧操作数的运算符(或没有可接受的转换)
根据this article,ActionId 的operator<() 成员具有const 资格应该足以使其成为自定义地图键,而this article 表示我所需要的只是使ActionId 可复制和可分配的。很明显,我的结构满足这两个条件,那为什么InputManager::keysBoundTo() 不能编译呢?
【问题讨论】:
-
你看错了地方。
map::operator[]不是const。