【发布时间】:2020-02-08 17:43:37
【问题描述】:
我正在尝试在 C++ 中克隆 std::map 类;我使用存储 std::pair 的 std::vector。现在我正在实现 [] 运算符。我做了两个定义,一个是不用修改就可以访问的const,一个不是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;
}
如果有人可以帮助我,我会很高兴。
【问题讨论】:
-
返回
const TValor&意味着这个重载只能在 constMap<TClau, TValor>上调用。如果是这样,请执行const TValor& operator[](const TClau& clau) const; -
@Nil folquer covarrubias 仅通过更改返回类型无法实现函数重载。您需要更改至少一个参数,或者您应该在这里做的是将返回
const引用的函数声明为本身为const,如const TValor& Map<TClau, TValor>::operator[](const TClau& clau) const。注意声明末尾的 const。 -
行得通。现在我有另一个问题。后来我制作了一张地图,其中 TClau 是另一个带有 operator== 的类。当我比较时,它给了我一个`二进制'==':没有找到接受左手操作数类型的运算符(或者没有可接受的转换)`有什么想法吗?
标签: c++ reference operator-overloading operators overloading