开发者

I overloaded operator > but it still says no operator matches operands

开发者 https://www.devze.com 2022-12-22 17:34 出处:网络
I need B class to have a min priority queue of AToTime objects. AToTime have operator>, and yet I receive error telling me than there is no operator> matching the operands...

I need B class to have a min priority queue of AToTime objects.

AToTime have operator>, and yet I receive error telling me than there is no operator> matching the operands...

#include <queue>
#include <functional>

using namespace std; 

class B
{
  public:
    B();
    virtual ~B();
  private:
    log4cxx::LoggerPtr m_logger;
    class AToTime 
    {
    public:
      AToTime(const ACE_Time_Value& time, const APtr a) : m_time(time), m_a(a){}

      bool operator >(const AToTime& other)
      {
        return m_time > other.m_time;
      }

    public:
      ACE_Time_Value m_time;
      APtr           m_a;
    };

    pri开发者_C百科ority_queue<AToTime, vector<AToTime>, greater<AToTime> > m_myMinHeap;
};


    bool operator >(const AToTime& other)

It should be a const function.

    bool operator >(const AToTime& other) const 


Kenny's answer already shows you how to make this work.

Note that I would prefer to implement binary operators which treat their operands equally (they're not modifying them) as free functions:

inline bool operator>(const AToTime& khs, const AToTime& rhs)
{
  return lhs.m_time > rhs.m_time;
}

Further, usually users expect all relational operators to be present if one of them is there. Since the std library mostly wants operator<, except for equality I'd implement the others on top of operator<:

inline bool operator<(const AToTime& khs, const AToTime& rhs)
{return lhs.m_time < rhs.m_time;}

inline bool operator>(const AToTime& khs, const AToTime& rhs)
{return rhs < lhs;}

inline bool operator<=(const AToTime& khs, const AToTime& rhs)
{return !(lhs > rhs);}

inline bool operator>=(const AToTime& khs, const AToTime& rhs)
{return !(lhs < rhs);}

inline bool operator==(const AToTime& khs, const AToTime& rhs)
{return lhs.m_time == rhs.m_time;}

inline bool operator!=(const AToTime& khs, const AToTime& rhs)
{return !(lhs.m_time == rhs.m_time);}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号