2011-09-02 102 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的

相關問題