2016-12-26 137 views
-3

Hy!這是我在這個網站上的第一個問題。對不起,我的英語,我是否會犯錯:(無效<運營商

所以,我的問題是下面,我簡單的類日期。

class Date 
{ 
public: 
    Date(); 
    Date(unsigned short day, unsigned short month, unsigned short year); 
    Date(const Date &date); 
    unsigned short getDay(); 
    unsigned short getMonth(); 
    unsigned short getYear(); 

    void setDay(unsigned short day); 
    void setMonth(unsigned short month); 
    void setYear(unsigned short year); 

void printOnScreen()const; 
friend 
    std::ostream& operator<< (std::ostream& out, const Date& date) { 
     out << date.day << "." << date.month << "." << date.year; 
     return out; 
    } 

friend 
    bool operator<(const Date& a, const Date& b) { 
     if (a == b) { 
      return false; 
     } 

     if (a.year < b.year) { 
      return true; 
     } 
     if (a.month < b.month) { 
      return true; 
     } 
     if (a.day < b.day) { 
      return true; 
     } 

     return false; 
} 

friend 
    Date& operator-(Date& a) { 
     return a; 
    } 

friend 
    Date operator-(const Date& a, const Date& b) { 
     return Date(
      abs(a.day - b.day), 
      abs(a.month - b.month), 
      abs(a.year - b.year) 
      ); 
    } 

friend 
    bool operator==(const Date& date1, const Date& date2) { 

     return (
      date1.day == date2.day && 
      date1.month == date2.month && 
      date1.year == date2.year 
      ); 
    } 

    virtual ~Date(); 
private: 
    friend KeyHasher; 

    unsigned short day; 
    unsigned short month; 
    unsigned short year; 
}; 

在我的主要功能我叫有點像在這個例子中,和後得到的錯誤。

auto dates = { 
    Date(1, 5, 2016), 
    Date(3, 2, 2015), 
    Date(3, 3, 2000), 
    Date(2, 1, 1991), 
    Date(1, 8, 2200), 
    Date(1, 8, 2200), 
    Date(1, 8, 2020), 
    Date(21, 9, 2016) 
}; 

vector<Date> v1(dates); 
sort(
    v1.begin(), 
    v1.end(), 
    less<Date>() 
); 

什麼是錯的,我不明白。謝謝你的幫助。

+4

如果你有編譯錯誤,總是包括他們在問題的機構。請編輯您的問題,以包含完整版本輸出,作爲複製粘貼文本,完整,未經編輯。 –

+0

請從Visual Studio的「輸出」選項卡中獲取錯誤消息的文本,並將其複製到問題中。 – drescherjm

+0

[No repro](http://coliru.stacked-crooked.com/a/597ebd0069e798e3) –

回答

2

operator <確實是不正確,使用std::tie

auto as_tuple(const Date& d) { 
    return std::tie(d.year, d.month, d.day); 
} 

bool operator<(const Date& lhs, const Date& rhs) { 
    return as_tuple(lhs) < as_tuple(rhs); 
} 

bool operator == (const Date& lhs, const Date& rhs) { 
    return as_tuple(lhs) == as_tuple(rhs); 
} 
1

試圖改變自己的條件,如:

if (a.year < b.year) 
    return true; 
else if (a.year > b.year) 
    return false; 
else // a.year == b.year 
{ 
    if (a.month < b.month) 
     return true; 
    else if (a.month > b.month) 
     return false; 
    else // a.month == b.month 
    { 
     if (a.day < b.day) 
      return true; 
     else 
      return false; 
    } 
} 
+0

當手動編寫代碼(而不是'std :: tie')時,我發現了更多的慣用法來做'if(a.year!= b .year){return a.year Jarod42