无效<操作者

时间:2016-12-26 13:40:59

标签: c++ c++11 visual-c++ operator-overloading c++14

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

在我的main函数中,我在这个例子中调用了sort,并在得到错误之后。

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>()
);

有什么不对,我不明白。谢谢你的帮助。

2 个答案:

答案 0 :(得分: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 :(得分: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;
    }
}