我有以下的私有成员的类:为什么运算符[]不允许映射但允许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数组?
的解决方案是使用'常量性的发现(const的重点和)常量相反。 –
谢谢,这使得完美的感觉:) – Arvin