2011-09-02 111 views
0

我有以下的私有成员的类:为什么运算符[]不允许映射但允许int数组?

private: 
    int *vals_; 
    size_type *cidx_; 
    std::map< size_type, std::pair<size_t, unsigned int> > ridx_; 

现在我想在运营商访问这些变量< <超载:(注意:m是常量

std::ostream& operator<<(std::ostream &os, const SMatrix &m) 
{ 
    os << m.cidx_[0] << endl; 
    os << m.ridx_[0].first << endl; 

    return os; 
} 

什么我发现m.cidx_ [0]会起作用,但m.ridx_ [0] .first会给出错误:

error: passing 'const std::map, std::less, std::allocator > > >' as 'this' argument of '_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = unsigned int, _Tp = std::pair, _Compare = std::less, _Alloc = std::allocator > >]' discards qualifiers

我认为这意味着operator []是一个修饰运算符,因此与m是const的事实相矛盾。但是为什么它对vals_和cidx_都是int和size_type数组?

回答

7

std::map::operator[]插入一个元素,如果它不存在,所以它不能与const对象一起使用。数组不是C++中的类类型,因为它们a[idx]等价于*(a + idx),并且决不会自变阵。

如果你通过地图容器的源代码
+1

的解决方案是使用'常量性的发现(const的重点和)常量相反。 –

+0

谢谢,这使得完美的感觉:) – Arvin

1

,没有地图::运算符[]与常量CV预选赛,但你的矩阵对象为const的

相关问题