【问题标题】:When using map::erase() "error: passing 'const ***' as 'this' argument of '***' discards qualifiers [-fpermissive]" reported使用 map::erase() 时“错误:将 'const ***' 作为 '***' 的 'this' 参数传递会丢弃限定符 [-fpermissive]”
【发布时间】:2016-02-27 22:35:37
【问题描述】:

我正在实现以下方法以使用 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
}

在标题中我定义了以下内容:

//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;
};

其中ObjPtrObjects 类型对象的虚拟指针。

编译时出现此错误:

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,我无法修改它。

【问题讨论】:

  • 不相关,但您可能希望通过 const-reference 而不是按值传递 nomobjetg。那是void Gestion::EliminateObject(const string&amp; nomobjetg)。如果那是一个 std::string,它会做一个浪费的字符串复制。

标签: c++ iterator erase qualifiers


【解决方案1】:

void Gestion::EliminateObject(string nomobjetg) const

您试图通过调用objectname.erase(it) 来修改objectname,而const 函数不允许您这样做,除非objectname可变

删除常量:

void Gestion::EliminateObject(string nomobjetg)

使objectname 可变

mutable Objectmap objectname;

【讨论】:

  • 谢谢!对于第一个选项,您是否建议将const 更改为*?为什么仅仅消除const 并不能解决问题?
  • * 是一个错字,我现在已经修正了...是的,我会删除 const。可变是针对某些特定情况的,在使用它之前你应该确保你需要的是一个可变数据成员......
猜你喜欢
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-13
相关资源
最近更新 更多