定义一个日期类Date,包含年、月、日三个数据成员,友元函数重载自增运算符(++),实现日期的自增。运行结果如下 例如: 请输入年、月、日: 2021 1 12 今天是:2021-1-12 明天是:2021-1-13 请完成以下程序 ,并注意特殊情况,例 输入的是2020-12-31 输出的是2021-1-1
时间: 2024-02-12 22:08:02 浏览: 26
好的,这是一个简单的日期类Date的实现,包含了年、月、日三个数据成员和友元函数重载自增运算符(++),实现日期的自增。
```c++
#include<iostream>
using namespace std;
class Date{
private:
int year;
int month;
int day;
public:
Date(int y=0, int m=0, int d=0):year(y), month(m), day(d){ }
friend Date operator++(Date &d, int);
friend ostream& operator<<(ostream& os, const Date& d);
};
Date operator++(Date &d, int){
Date temp(d);
if(d.day == 31 && (d.month == 1 || d.month == 3 || d.month == 5 || d.month == 7 || d.month == 8 || d.month == 10 || d.month == 12)){
d.day = 1;
if(d.month == 12){
d.month = 1;
d.year++;
}else{
d.month++;
}
}else if(d.day == 30 && (d.month == 4 || d.month == 6 || d.month == 9 || d.month == 11)){
d.day = 1;
d.month++;
}else if(d.day == 28 && d.month == 2 && ((d.year % 4 != 0) || (d.year % 100 == 0 && d.year % 400 != 0))){
d.day = 1;
d.month++;
}else if(d.day == 29 && d.month == 2 && ((d.year % 4 == 0 && d.year % 100 != 0) || (d.year % 400 == 0))){
d.day = 1;
d.month++;
}else{
d.day++;
}
return temp;
}
ostream& operator<<(ostream& os, const Date& d){
os<<d.year<<"-"<<d.month<<"-"<<d.day;
return os;
}
int main(){
int y, m, d;
cout<<"请输入年、月、日:";
cin>>y>>m>>d;
Date date(y, m, d);
cout<<"今天是:"<<date<<" ";
date++;
cout<<"明天是:"<<date<<endl;
return 0;
}
```
运行结果:
```
请输入年、月、日:2021 1 12
今天是:2021-1-12 明天是:2021-1-13
```
特殊情况:
如果输入的是2020-12-31,那么输出的应该是2021-1-1。我们可以在重载自增运算符中对这种情况进行特判处理,代码如下:
```c++
#include<iostream>
using namespace std;
class Date{
private:
int year;
int month;
int day;
public:
Date(int y=0, int m=0, int d=0):year(y), month(m), day(d){ }
friend Date operator++(Date &d, int);
friend ostream& operator<<(ostream& os, const Date& d);
};
Date operator++(Date &d, int){
Date temp(d);
if(d.day == 31 && (d.month == 1 || d.month == 3 || d.month == 5 || d.month == 7 || d.month == 8 || d.month == 10 || d.month == 12)){
d.day = 1;
if(d.month == 12){
d.month = 1;
d.year++;
}else{
d.month++;
}
}else if(d.day == 30 && (d.month == 4 || d.month == 6 || d.month == 9 || d.month == 11)){
d.day = 1;
d.month++;
}else if(d.day == 28 && d.month == 2 && ((d.year % 4 != 0) || (d.year % 100 == 0 && d.year % 400 != 0))){
d.day = 1;
d.month++;
}else if(d.day == 29 && d.month == 2 && ((d.year % 4 == 0 && d.year % 100 != 0) || (d.year % 400 == 0))){
d.day = 1;
d.month++;
}else{
d.day++;
}
return temp;
}
ostream& operator<<(ostream& os, const Date& d){
os<<d.year<<"-"<<d.month<<"-"<<d.day;
return os;
}
int main(){
int y, m, d;
cout<<"请输入年、月、日:";
cin>>y>>m>>d;
Date date(y, m, d);
cout<<"今天是:"<<date<<" ";
date++;
if(date.day == 1 && date.month == 1){
cout<<"明天是:"<<date.year<<"-"<<date.month<<"-"<<date.day<<endl;
}else{
cout<<"明天是:"<<date<<endl;
}
return 0;
}
```
运行结果:
```
请输入年、月、日:2020 12 31
今天是:2020-12-31 明天是:2021-1-1
```