【问题标题】:How can I differenciate this two operator overloading?如何区分这两个运算符重载?
【发布时间】: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&amp; 意味着这个重载只能在 const Map&lt;TClau, TValor&gt; 上调用。如果是这样,请执行const TValor&amp; operator[](const TClau&amp; clau) const;
  • @Nil folquer covarrubias 仅通过更改返回类型无法实现函数重载。您需要更改至少一个参数,或者您应该在这里做的是将返回const 引用的函数声明为本身为const,如const TValor&amp; Map&lt;TClau, TValor&gt;::operator[](const TClau&amp; clau) const。注意声明末尾的 const。
  • 行得通。现在我有另一个问题。后来我制作了一张地图,其中 TClau 是另一个带有 operator== 的类。当我比较时,它给了我一个`二进制'==':没有找到接受左手操作数类型的运算符(或者没有可接受的转换)`有什么想法吗?

标签: c++ reference operator-overloading operators overloading


【解决方案1】:

这些运算符仅在返回类型上有所不同。

TValor& operator[](const TClau& clau);
const TValor& operator[](const TClau& clau);

第二个运算符应使用限定符 const 声明

const TValor& operator[](const TClau& clau) const;

在这种情况下,运算符的声明是不同的。

第一个操作符会被一个非常量对象调用,第二个操作符会被一个常量对象调用。

【讨论】:

  • 行得通。现在我有另一个问题。后来我制作了一张地图,其中 TClau 是另一个带有 operator== 的类。当我比较时,它给了我一个`二进制'==':没有找到接受左手操作数类型的运算符(或没有可接受的转换)`有什么想法吗?
  • @Nilfolquercovarrubias 这是另一个问题。关闭当前问题并创建一个新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
  • 2012-09-08
  • 1970-01-01
  • 2023-03-14
相关资源
最近更新 更多