当对象是集合成员时,c++ std::set 比较函数

问题描述 投票:0回答:1

我有一组由对象组成的集合;为了工作,必须定义

operator<
来对集合内的对象进行排序。如果我将
operator<
定义为友元函数,它就可以工作;如果我将
operator<
定义为成员函数,则会收到错误:

错误 C2678 二进制“<': no operator found which takes a left-hand >类型为‘const _Ty’的操作数(或者没有可接受的转换)。

我不明白为什么作为成员函数实现的

operator<
版本不起作用/应该更改什么。 我在下面提供了问题案例的简化示例:

class TestObj
{
private: 
    int m_a;
public:
    TestObj(int a): m_a{a} {}
    /* operator < as friend function works */
    /*friend bool operator< (const TestObj& t1, const TestObj& t2)
    {
        return t1.m_a < t2.m_a;
    }*/
    /* operator < as member function does not work! */
    bool operator< (const TestObj& t2)
    {
        return m_a < t2.m_a;
    }
};
void testSetCompare()
{
    std::set<TestObj> set1;
    set1.insert(10);
    set1.insert(20);
}

我不明白为什么作为成员函数实现的

operator<
版本不起作用/应该更改什么。

c++ set compare
1个回答
3
投票

您需要创建成员函数

const
。因为您将其声明为“非常量”,所以编译器无法决定您的运算符是否会更改
*this
,因此当您有
const TestObj&
时,无法使用您的运算符。

bool operator< (const TestObj& t2) const
{
    return m_a < t2.m_a;
}

它会完成这项工作。

编辑:“不可接受的转换”意味着它无法从

const TestObj&
转换为
TestObj&
,因为这会违反
const
的规则(并且您的操作员需要
TestObj&
)。

© www.soinside.com 2019 - 2024. All rights reserved.