我正在尝试在c ++中克隆std :: map类;我使用存储std :: pair的std :: vector。现在,我正在实现[]运算符。我做了两个定义,一个是未经修改的acces常量,另一个不是const。
编译时告诉我没有区别。
这是声明: 使用此模板:
template<class TClau, class TValor>
TValor& operator[](const TClau& clau);
const TValor& operator[](const TClau& clau);
这是定义:
//m_map is the actual vector with pairs.
template<class TClau, class TValor>
TValor& Map<TClau, TValor>::operator[](const TClau& clau) {
int l = 0, r = m_length - 1;
int m;
if (r >= l) {
while (r >= l) {
m = l + (r - l) / 2;
if (m_map[m] == clau)
return m_map[m].second;
if (m_map[m] > clau)
r = m - 1;
l = m + 1;
}
}
return TValor;
}
template<class TClau, class TValor>
const TValor& Map<TClau, TValor>::operator[](const TClau& clau) {
int l = 0, r = m_length - 1;
int m;
if (r >= l) {
while (r >= l) {
m = l + (r - l) / 2;
if (m_map[m] == clau)
return m_map[m].second;
if (m_map[m] > clau)
r = m - 1;
l = m + 1;
}
}
return aux;
}
如果有人可以帮助我,我将表示感谢。
答案 0 :(得分:4)
这些运算符的区别仅在于返回类型。
TValor& operator[](const TClau& clau);
const TValor& operator[](const TClau& clau);
第二个运算符应使用限定符const声明
const TValor& operator[](const TClau& clau) const;
在这种情况下,运算符的声明是不同的。
第一个运算符将被用于非常量对象,第二个运算符将被用于常量对象。