版权声明:本文为博主原创文章,转载时请注明原作者,谢谢! https://blog.csdn.net/qq_31112205/article/details/84838498
这篇博客主要是学习C++程序设计语言有关类定义,成员函数,成员变量及运算符重载定义的知识,并没有具体去实现什么,只是学习它的语法什么的。
Date.h文件代码:
#include<string>
#include<iostream>
class Date{
public:
enum Month {jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
class Bad_date{};//异常类
Date(int dd=0,Month mm=Month(0),int yy=0);//0的意思是“取默认值”
int day() const;
Month month() const;
int year() const;
std::string string_rep() const; //字符串表示
void char_rep(char s[]) const; //C风格的字符串表示
static void set_default(int,Month,int);
Date& add_year(int);
Date& add_month(int);
Date& add_day(int);
private:
int y, m, d;
static Date default_date;
};
inline int Date::day() const {return d;}
inline Date::Month Date::month() const {return Month(m);}
inline int Date::year() const {return y;}
//运算符重载,可以定义到函数内,但是参数只能有一个;也可以定义为友元函数
bool operator==(Date,Date );
bool operator<(Date,Date);
bool operator>(Date,Date);
Date& operator++(Date& d);
Date& operator--(Date& d);
Date& operator+=(Date& d,int n);
Date& operator-=(Date& d,int n);
Date& operator+(Date d,int n);
Date& operator-(Date d,int n);
std::ostream& operator<<(std::ostream&,Date d);
std::istream& operator>>(std::istream&,Date& d);
//协助函数,可以将协助函数和类Date放到一个命名空间内
int diff(Date a,Date b);
bool leapyear(int y);
Date next_weekday(Date d);
Date next_saturday(Date d);
Date.cpp文件代码:
#include"Date.h"
#include<iostream>
Date::Date(int dd, Month mm, int yy)
{
if(yy==0) yy=default_date.year();
if(mm==0) mm=default_date.month();
if(dd==0) dd=default_date.day();
int max;
switch(mm){
case feb:
max = 28+leapyear(yy);
break;
case apr:case jun:case sep:case nov:
max=30;
break;
case jan:case mar:case may:case jul:case aug:case oct:case dec:
max=31;
break;
default:
throw Bad_date();
}
if(dd<1||max<dd) throw Bad_date();
y=yy;
m=mm;
d=dd;
}
bool leapyear(int y)
{
if(((y%400)==0)||(((y%100)!=0)&&((y%4)==0)))
return true;
return false;
}
Date& Date::add_year(int n)
{
y += n;
return *this;
}
Date& Date::add_month(int n)
{
if(n==0) return *this;
if(n>0){
int delta_y = n / 12;
int mm = m + n % 12;
if(12<mm){
delta_y++;
mm -= 12;
}
y += delta_y;
m = Month(mm);
return *this;
}
return *this;
}
Date& Date::add_day(int n)
{
int mon_day[] = {31,28,31,30,31,30,31,31,30,31,30,31};
if(leapyear(this->y))
mon_day[1] += 1;
if(d+n<=mon_day[m-1])
{
d += n;
return *this;
}
n = (n+d)-mon_day[m-1];
d = 0;
m += 1;
if(12<m)
{
m = 1;
y += 1;
}
add_day(n);
}