我正在尝试用 C++ 克隆 std::map 类;我使用存储 std::pair 的 std::vector。现在我正在实现 [] 运算符。我做了两个定义,一个是const to access without modifying,一个不是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;
}
如果有人可以帮助我,我会很感激。
最佳答案
这些运算符仅在返回类型上有所不同。
TValor& operator[](const TClau& clau);
const TValor& operator[](const TClau& clau);
第二个运算符应该用限定符 const 声明
const TValor& operator[](const TClau& clau) const;
在这种情况下,运算符的声明是不同的。
将为非常量对象调用第一个运算符,为常量对象调用第二个运算符。
关于c++ - 我如何区分这两个运算符重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58337139/