【问题标题】:Why should operator< be defined as non-member?为什么要将 operator< 定义为非成员?
【发布时间】:2013-05-13 03:37:44
【问题描述】:

我对 hash_map 做了一些测试,使用 struct 作为键。我定义结构:

struct ST
{

    bool operator<(const ST &rfs)
    {
        return this->sk < rfs.sk;
    }

    int sk;
};

和:

size_t hash_value(const ST& _Keyval)
{   // hash _Keyval to size_t value one-to-one
    return ((size_t)_Keyval.sk ^ _HASH_SEED);
}

然后:

stdext::hash_map<ST, int> map;
ST st;
map.insert(std::make_pair<ST, int>(st, 3));

它给了我一个编译器错误:二进制'

所以我将运营商改为非会员:

bool operator<(const ST& lfs, const ST& rfs)
{
    return lfs.sk < rfs.sk;
}

没关系。所以我想知道为什么?

【问题讨论】:

    标签: c++ map hashmap


    【解决方案1】:

    你错过了const

    bool operator<(const ST &rfs) const
    {
        return this->sk < rfs.sk;
    }
    

    【讨论】:

    • 是的,我检查了抛出错误的地方。'bool operator()(const _Ty& _Left, const _Ty& _Right) const'。当然,我想念 const。
    • @MIKU​​_LINK:是的,这是能够调用const ST 对象上的操作员所必需的。
    【解决方案2】:

    我认为问题是

    error:binary ''const ST' 类型的左操作数(或没有可接受的转换)

    您的成员函数 bool operator&lt;(const ST &amp;rfs) 被声明为非常量,因此不能针对 const ST 调用它。

    只需将其更改为 bool operator&lt;(const ST &amp;rfs) const 就可以了

    【讨论】:

      【解决方案3】:

      尽管有以上答案,我建议你看看:

      C++ Primer,第四版,第 14 章,第 14.1 节

      通常我们将算术和关系运算符定义为 非成员函数,我们将赋值运算符定义为成员:

      【讨论】:

        猜你喜欢
        • 2021-05-24
        • 1970-01-01
        • 2011-07-19
        • 2017-01-13
        • 2014-04-20
        • 2018-07-30
        • 1970-01-01
        • 2010-09-23
        相关资源
        最近更新 更多