我正在实现以下方法,使用 map::erase()
从关联表 (map
) 中删除一个元素:
//Method in gestion.cpp
void Gestion::EliminateObject(string nomobjetg) const{
auto it = objectname.find(nameobjectg);
if (it == objectname.end())
cout << "Object not found!" << endl;
else
objectname.erase(it); //The error is reported in this line
}
在 header 中我定义了以下内容:
//gestion.h
#include "objects.h"
#include <list>
#include <iostream>
#include <string>
#include <memory>
#include <map>
using namespace std;
typedef std::shared_ptr<Objects> ObjPtr;
typedef map<string, ObjPtr> Objectmap;
class Gestion
{
private:
Objectmap objectname;
public:
Gestion(Objectmap objectname, Groupmap groupname);
virtual ~Gestion() {}
virtual void EliminateObject(string nameobjectg) const;
};
其中 ObjPtr
是 Objects
类型对象的虚拟指针。
当我编译时出现这个错误:
error: passing ‘const Objectmap {aka const std::map<std::basic_string<char>, std::shared_ptr<Objects> >}’ as ‘this’ argument of ‘std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::erase(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator) [with _Key = std::basic_string<char>; _Tp = std::shared_ptr<Objects>; _Compare = std::less<std::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::basic_string<char>, std::shared_ptr<Objects> > >; std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, std::shared_ptr<Objects> > >; std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator = std::_Rb_tree_const_iterator<std::pair<const std::basic_string<char>, std::shared_ptr<Objects> > >]’ discards qualifiers [-fpermissive]
objectname.erase(it);
为什么这一行会报这个错?我已经看到其他一些帖子出现此类错误,但在那些情况下,问题的根本原因与方法的声明方式 (const
) 有关。在这种情况下,问题涉及的方法是erase
,我无法修改它。
最佳答案
void Gestion::EliminateObject(string nomobjetg) const
您正在尝试通过调用 objectname.erase(it)
来修改 objectname
,而 const
函数不允许您这样做除非 objectname
是可变的。
删除常量:
void Gestion::EliminateObject(string nomobjetg)
或
使objectname
可变
mutable Objectmap objectname;
关于c++ - 当使用 map::erase() "error: passing ' const ** *' as ' '***' 的这个参数丢弃限定符 [-fpermissive]”报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35676311/