c++ - 错误:'operator<' 不匹配(操作数类型为 'const A' 和 'const A')
问题描述
#include <set>
#include <iostream>
using namespace std;
template<class T>
class A
{
public:
A(T a = 0,T b =0): m_a(a),m_b(b) {}
bool operator<(const A& lhs)
{
/* compare code */
}
private:
T m_a;
T m_b;
};
int main()
{
A<int> abc(2,3);
set<A<int>> P2D;
P2D.insert(abc);
return 0;
}
当我运行此代码时,出现以下错误
操作数类型为 'const A' 和 'const A'</p>
如果我const
在重载上声明关键字operator<
:
bool operator<(const A& lhs) const
{
/* compare code */
}
它没有给出错误,但是:
- 我在这里有什么遗漏吗?
const
如果我不声明关键字,为什么会出错?
解决方案
您operator<
需要是const
,因为在内部set
对const
对象进行操作。
此外,operator<
无论如何,您的实施都没有正确。它忽略了A
比较左侧对象的成员,它只查看A
右侧对象的成员。
试试这个:
#include <set>
#include <iostream>
using namespace std;
template<class T>
class A
{
public:
A(T a = T(), T b = T()): m_a(a), m_b(b) {}
bool operator<(const A& rhs) const
{
return ((m_a < rhs.m_a) ||
((m_a == rhs.m_a) && (m_b < rhs.m_b))
);
/* alternatively:
return std::tie(m_a, m_b) < std::tie(rhs.m_a, rhs.m_b);
*/
}
private:
T m_a;
T m_b;
};
int main()
{
A<int> abc(2,3);
set<A<int>> P2D;
P2D.insert(abc);
return 0;
}
推荐阅读
- javascript - Gatsby 配置不改变颜色主题
- python - 使用预训练模型的 BERT 句子嵌入非英语文本
- xml - 使用块中的 xmlstarlet 从同一节点获取多个子注释
- sql-server - 如何使用多个子表运行循环 SQL
- c# - 为什么 UpdatePanel 触发器无法识别我的 ControlID
- python-3.x - 如何在自定义条目对象上编辑 tkinter 字体属性?
- swift - Swift:精确到 timeIntervalSince1970
- python - 在字典中提取特定的嵌套值
- c++ - 无法实现按名称搜索
- python - Python - 操作系统模块'TypeError:'bool'对象不可迭代''