2011-09-02 4 views
0

다음 private 멤버가있는 클래스가 있습니다.왜 operator []가 맵에는 허용되지 않지만 int 배열에는 허용됩니까?

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

이제 연산자 <에서 이러한 변수에 액세스하려고합니다. < 오버로드 : ( m은 const입니다.)

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

    return os; 
} 

find는 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

저는 연산자 []가 수정 연산자라는 것을 의미하므로 m이 const. 하지만 int 및 size_type 배열 인 vals_ 및 cidx_는 왜 작동합니까?

답변

7

std::map::operator[]은 요소가 없으면 삽입하므로 개체는 const과 함께 사용할 수 없습니다. 배열은 C++에서 클래스 유형이 아니기 때문에 a[idx]*(a + idx)과 동일하며 배열 자체를 변경하지 않습니다.

+1

솔루션이 사용하는'const_iterator를 찾기 (CONST 키 &) const를 CONST입니다 '대신. –

+0

고마워, 그 말이 완벽 해. :) – Arvin

1

당신이지도 컨테이너의 소스 코드를 보면은, CONST 이력서 규정 아무지도 :: 연산자 []가 없지만, 당신의 행렬 객체는

관련 문제