c++ - 我如何区分这两个运算符重载?

标签 c++ reference operator-overloading operators overloading

我正在尝试用 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/

相关文章:

c++ - 将所有模板类型传递给运算符而不指定所有类型

c# - 术语 "reference"的起源与 "pass-by-reference"

c++ - 无法从友元函数访问类的私有(private)成员? 'ostream' 不是 'std' 的成员?

c++ - 如何调用算子模板?

c++ - C++ 编译器必须选择两个转换运算符中的哪一个?

同一命名空间内的 C++ 函数调用

c++ - 当类想要耦合

php - 为什么当 PHP 数组的元素是引用分配时它会被修改?

c++ - 为什么使用 'new'会导致内存泄漏?

c# - .NET 项目中的条件引用是否可以消除警告?