构造一个日期类Date要求重载:流提取和流插入运算符重载前置和后置自增运算符
#include <iostream>
using namespace std;
class Date {
private:
int year, month, day;
public:
Date(int y = 1970, int m = 1, int d = 1) {
year = y;
month = m;
day = d;
}
friend ostream& operator<<(ostream& os, const Date& date) {
os << date.year << '-' << date.month << '-' << date.day;
return os;
}
friend istream& operator>>(istream& is, Date& date) {
is >> date.year >> date.month >> date.day;
return is;
}
Date& operator++() { // 前置自增
day++;
if (day > getMonthDays()) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
}
}
return *this;
}
Date operator++(int) { // 后置自增
Date date(*this);
day++;
if (day > getMonthDays()) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
}
}
return date;
}
int getMonthDays() const {
if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 29;
}
else {
return 28;
}
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
}
else {
return 31;
}
}
};
int main() {
Date date(2022, 12, 31);
cout << date++ << endl; // 后置自增
cout << ++date << endl; // 前置自增
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/fINa 著作权归作者所有。请勿转载和采集!