一个Date类之比较日期大小
Date类是在c++学习中比较重要和比较常见的一个类,并在其中可以加入许多c++中的内容使其更加的完善,用途更多。我在里面呢加入了一些运算符的重载,进行日期大小的比较,上代码(运行环境vs2019)
#include<iostream>
using namespace std;
class date {
private:
int year, month, day;
public:
date(int y = 2020, int m = 5, int d = 1)
{
year = y;month = m;day = d;
}
int get_year(void) { return year; }
int get_month(void) { return month; }
int get_day(void) { return day; }
bool operator==(date p);
bool operator>(date p);
bool operator<(date p);
bool operator!=(date p);
bool operator>=(date p);
bool operator<=(date p);
//void compare(date& p1, date& p2);
friend istream& operator>>(istream& is, date& p);
friend ostream& operator<<(ostream& os, date& p);
};
bool date::operator==(date p)
{
return (year == p.year && month == p.month && day == p.day);
}
bool date::operator>(date p)
{
return (year > p.year || (year == p.year && month > p.month || (year == p.year && month == p.month && day > p.day)));
}
bool date::operator<(date p)
{
return (year < p.year || (year == p.year && month < p.month) || (year == p.year && month == p.month && day < p.day));
}
bool date::operator!=(date p)
{
return (year != p.year || month != p.month || day != p.day);
}
bool date::operator>=(date p)
{
return(*this == p || *this > p);
}
bool date::operator<=(date p)
{
return (*this == p || *this < p);
}
/*void date::compare(date& p1, date& p2)
{
if (p1 == p2) cout << p1.year << "-" << p1.month << "-" << p1.day << "==" << p2.year << "-" << p2.month << "-" << p2.day << endl;
if (p1 > p2) cout << p1.year << "-" << p1.month << "-" << p1.day << ">" << p2.year << "-" << p2.month << "-" << p2.day << endl;
if (p1 < p2) cout << p1.year << "-" << p1.month << "-" << p1.day << "<" << p2.year << "-" << p2.month << "-" << p2.day << endl;
if (p1 >= p2) cout << p1.year << "-" << p1.month << "-" << p1.day << ">=" << p2.year << "-" << p2.month << "-" << p2.day << endl;
if (p1 <= p2) cout << p1.year << "-" << p1.month << "-" << p1.day << "<=" << p2.year << "-" << p2.month << "-" << p2.day << endl;
if (p1 != p2) cout << p1.year << "-" << p1.month << "-" << p1.day << "!=" << p2.year << "-" << p2.month << "-" << p2.day << endl;
}*/
// 这块内容可用输出(<<)运算符的重载代替,是代码更加简洁,可用性增强;
istream& operator>>(istream& is, date& p)
{
cout << "year:";is >> p.year;cout << "month:";is >> p.month;cout << "day:";is >> p.day; return is;
}
ostream& operator<<(ostream& os, date& p)
{
os << p.year << p.month<< p.day;
return os;
}
int main()
{
date p1(2020, 5, 17), p2, p;
while (1)
{
cin >> p2;
if (p2.get_year() <= 0 || (p2.get_month() <= 0 || p2.get_month() > 12) || (p2.get_day() <= 0 || p2.get_day() > 31))
{
cout << "输入有误";
break;
}
//p.compare(p1, p2);
if (p1 == p2) cout << p1 << "==" << p2 << endl;
if (p1 > p2) cout << p1<< ">" << p2 << endl;
if (p1 < p2) cout << p1<< "<" << p2 << endl;
if (p1 >= p2) cout << p1<< ">=" << p2<< endl;
if (p1 <= p2) cout << p1 << "<=" << p2 << endl;
if (p1 != p2) cout << p1 << "!=" << p2 << endl;
}
return 0;
}
运算符重载不仅可以使代码更加简洁,而且使运行效率更高,便于读者的理解.
注:如有错误请指正。