为什么编译器说我不能将项插入到 std::set 中<Item>?

Why does the compiler say I can't insert an Item into a std::set<Item>?

本文关键字:set lt gt Item std 编译器 不能 插入 为什么      更新时间:2023-10-16

我有一个名为"Item"的类,我正在尝试将一个项目插入到一组项目中。

std::set<Item>::iterator it;
_items.insert(it, newItem);

但它给了我这个奇怪的错误

Error   1   error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Item' (or there is no acceptable conversion)

即使我确实实现了这个运算符。

bool Item::operator<(Item& other)
{
    return _serialNumber < other._serialNumber;
}

我不明白为什么我在这个函数中需要这个运算符。

有人知道问题出在哪里吗?

提前感谢!

您应该将定义更改为:-

bool Item::operator<( const Item& other)  const
                      ^^^^^               ^^^^^
{
    return _serialNumber < other._serialNumber;
}

"我不明白为什么我在这个函数中需要这个运算符。

这是因为您需要确保在 Item 类的 rvalue 实例上调用此运算符函数。这是std::set(以及其他容器类,其中Item应用作键)的要求。