2010-03-14 71 views
3

我需要B類具有AToTime對象的最小優先級隊列。我重載操作符>但它仍然表示沒有操作符匹配操作數

AToTime有operator>,但我收到錯誤告訴我,不是沒有運營商>匹配的操作數...

#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; 
    }; 

    priority_queue<AToTime, vector<AToTime>, greater<AToTime> > m_myMinHeap; 
}; 
+2

作爲一般性評論,發佈提問時,儘量減少空間的代碼需要(試圖儘可能多地使用代碼),同時保持可讀性。嘗試通過刪除與問題無關的代碼(記錄器定義)無用的評論('private私人成員'就在'私人'不提供任何內容之前]並壓縮它們'public://使用私有成員的無用點這裏'如果他們添加信息。這同樣適用於免費的額外空間(在'priority_queue'定義之前的兩條空行) – 2010-03-14 10:56:31

回答

9
bool operator >(const AToTime& other) 

這應該是一個const函數。

​​
1

Kenny's answer已經告訴你如何使這項工作。

注意,我寧願實現二元運算符同等地對待自己的操作數(他們沒有對其進行修改)免費功能:

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

此外,通常用戶所期望的,如果一個所有關係運算符是存在他們在那裏。由於STD庫大多希望operator<,除了平等我實現其他人的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

您不需要手動定義這些空間。它們在效用中被定義。你只需要包含它們並使用它們。 「using namespace std :: rel_ops;」 http://www.cplusplus.com/reference/std/utility/rel_ops/ – 2010-03-14 17:36:23

+0

@Martin:這些問題的一個潛在的問題是,你得到他們的名字空間中的所有類型。我沒有看到他們在野外使用,也沒有使用他們自己。他們用過嗎? (也許這會產生一個很好的CW問題?) – sbi 2010-03-14 20:02:42