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