完成日期类CDate{ CDate(); CDate (int year,int month,int day); CDate operator ++(); CDate operator ++(int); CDate operator +(long days) const; CDate operator -(long days) const; long operator -(const CDate &rhs) const; int WeekDay() const; static
时间: 2023-06-03 18:04:52 浏览: 204
mdatepp:mdate ++,cdate对mdate的重写
&dt) const;}的定义中,operator-()返回两个日期之间相差的天数,您能否给出具体实现方法?
可以的。具体的实现方法如下:
```cpp
#include<cmath>
class CDate{
int year,month,day;
public:
CDate();
CDate(int year,int month,int day);
CDate operator+(int days);
CDate operator-(int days);
int operator-(CDate otherDate);
};
CDate::CDate(){
year=2000;
month=1;
day=1;
}
CDate::CDate(int year,int month,int day){
this->year=year;
this->month=month;
this->day=day;
}
CDate CDate::operator+(int days){
CDate result=(*this);
int i;
for(i=1;i<=days;i++){
result.day++;
if(result.day>days_in_month[result.month]+(result.month==2&&isleapyear(result.year))){
result.day=1;
result.month++;
if(result.month>12){
result.month=1;
result.year++;
}
}
}
return result;
}
CDate CDate::operator-(int days){
CDate result=(*this);
int i;
for(i=1;i<=days;i++){
result.day--;
if(result.day<1){
result.month--;
if(result.month<1){
result.month=12;
result.year--;
}
result.day=days_in_month[result.month]+(result.month==2&&isleapyear(result.year));
}
}
return result;
}
int CDate::operator-(CDate otherDate){
int i,days=0;
if(otherDate>(*this)){
for(i=year;i<otherDate.year;i++){
days+=isleapyear(i)?366:365;
}
for(i=1;i<otherDate.month;i++){
days-=days_in_month[i]+(otherDate.year%4==0&&otherDate.month==2);
}
days-=otherDate.day;
for(i=1;i<month;i++){
days+=days_in_month[i]+(year%4==0&&month==2);
}
days+=day;
}else{
for(i=otherDate.year;i<year;i++){
days+=isleapyear(i)?366:365;
}
for(i=1;i<month;i++){
days-=days_in_month[i]+(year%4==0&&month==2);
}
days-=day;
for(i=1;i<otherDate.month;i++){
days+=days_in_month[i]+(otherDate.year%4==0&&otherDate.month==2);
}
days+=otherDate.day;
}
return days;
}
```
其中,`days_in_month`数组记录了每个月的天数,`isleapyear()`函数判断某一年是否是闰年。实现中,我们先判断目标日期与当前日期之间相差多少天,然后再根据目标日期是前还是后,分别计算即可。
阅读全文