创建一个名为Date(日期的类,包括了数据成员的3部分信息:月(类型int)、日(类型int)、年(类型int)

2020-10-06 社会 566阅读
#ifndef HEADER_DATE
#define HEADER_DATE
#include
#include
#include
using namespace std;
class date{
int year,month,day;
void init();
public:
static const int tians[];
int age();
int getyear()
int getmonth()
int getday()
date();
date(const string& s);
date(const date& d)
date(int y=2000,int m=1,int d=1);
bool isleapyear()const;
friend ostream& operator<<(ostream& o,const date& d);
double xg();
double xiangge(date b);
friend  date operator+=(date& a,int n);
friend bool operator==(date& a,date & b);
void display();
string huanyuan();
};
#endif
#include"date.h"
//日期的计算
const int date::tians[]=;
const long int year4=1461;
const long int year100=36524;
const long int year400=146097;
using namespace std;
void date::init(){
if(year>5000||month>12||day>31||day<1||month<1||year<1)
{cout<<"年月日范围出错!"<exit(1);
}
}
date::date(int y,int m, int d):year(y),month(m),day(d){
init();
}
date::date(const string& s):da(s){
year=atoi(s.substr(0,4).c_str());
month=atoi(s.substr(5,2).c_str());
day=atoi(s.substr(8,2).c_str());
}
bool date::isleapyear()const{
if(year%4==0&& year%100!=0 ||year%400==0)
return true;
return false;
}
ostream& operator<<(ostream& o,const date& d){
o<return o;
}
date operator+=(date& a,int n){
switch(a.month){
case 4:
case 6:
case 9:
case 11:else a.day+=n;if(a.month>12) break;}
case 2:
if((a.year%4==0 && a.year%100!=0 )||a.year%400==0)
 else a.day+=n;if(a.month>12)break;}
else {
if(a.day+n>28)else a.day+=n;if(a.month>12)}break;
}
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:else a.day+=n; if(a.month>12)}break; }
return a;
}
double date::xg(){
int days1[12]=;
long int sum1;            //4年一共1461天
sum1=year/400*year400+year%400/100*year100+year%400%100/4*year4+year%400%100%4*365;  //年份转换为天数所得
for(int i=0;i<12;i++)
if(month-1==i) sum1+=days1[i]+day;
return sum1;
}
double date::xiangge(date b){
return (xg()-b.xg());
}
bool operator==(date& a,date & b){
if(a.year==b.year && a.month==b.month&& a.day==b.day) return 1;
else return 0;
}
void date::display(){
cout<}
date::date(){  //无参为系统时间
 time_t timer;
 struct tm* t_tm;
 time(&timer);
 t_tm=localtime(&timer);
  year=t_tm->tm_year+1900,
  month=t_tm->tm_mon+1,
  day=t_tm->tm_mday;
  }
int date::age(){           //计算当前时间差
 time_t timer;
 struct tm* t_tm;
 time(&timer);
 t_tm=localtime(&timer);
 int y=t_tm->tm_year+1900,
  m=t_tm->tm_mon+1,
  d=t_tm->tm_mday;
 if(m else return (y-year);
}
string date::huanyuan(){
string m; char a1[10],b1[10], c1[10];
itoa(year, a1, 10);
itoa(month,b1, 10);
itoa(day, c1, 10);
m+=a1;
m+='/';
m+=b1;
m+='/';
m+=c1;
return m;
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com