我无法用我的实际知识解决一个转瞬即逝的常数错误



当键类型和值类型相同时,我对双向映射进行了专门化。我还为operator[]做了两个定义,一个返回常数,一个返回非常数。但这并没有解决我的问题。我得到一个错误,我传递常量为*this…

这是专门化:

template<class A>
class BidirectionalMap<A,A>
{
public:
    void insert(A a,A b)
    {
        m1.insert(std::pair<A,A> (a,b));
        m1.insert(std::pair<A,A> (b,a));
    }
    BidirectionalMap& operator =(BidirectionalMap &a)
    {
        m1=a.m1;
        return *this;
    }
    const A& at(const A& a) const
    {
        return m1.at(a);
    }
    int size() const
    {
        return m1.size();
    }
    int count(const A& a) const
    {
        return m1.count(a);
    }
    A& operator[](const A& a)
    {
        return m1[a];
    }
    const A& operator[](const A& a) const
    {
        return m1[a];////here pinpoints me that error: passing 'const std::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > >' as 'this' argument of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = int; _Tp = int; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, int> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = int; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]' discards qualifiers [-fpermissive]
    }
private:
    std::map<A,A> m1;
};

错误显示在这个上下文中:

  BidirectionalMap<int, int> f;
  f.insert(3, 18);
  f.insert(8, 2);
  f.insert(7, 5);
  f.insert(9, 1);
  const BidirectionalMap<int, int> cf = f;
  if( f.at(5) == 7 &&
      f.count(12) == 0 &&
      f.at(8) == 2)
  {
    yourMark = cf[18] + cf[9];//here is the error
  }

任何想法?

operator[]在std::map中通常不是const见http://www.cplusplus.com/reference/map/map/operator%5B%5D/

原因是operator[]允许在元素不存在时插入

相关内容

最新更新