首页 > 解决方案 > 错误:'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 */
}

它没有给出错误,但是:

  1. 我在这里有什么遗漏吗?
  2. const如果我不声明关键字,为什么会出错?

标签: c++oopsetconstantsoperator-overloading

解决方案


operator<需要是const,因为在内部setconst对象进行操作。

此外,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;   
}

在线演示


推荐阅读