2016-12-26 3 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

[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年){a.year Jarod42

関連する問題