Demo Code
class Date{
public:
class Year{
public:
Year(){
y = 1900;
}
uint16_t y;
bool isLeapYear(){
return ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0));
}
};
class Month{
public:
uint8_t m;
Month(){
m = 1;
}
uint8_t getDayCount(Year _y){
switch (m){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
return _y.isLeapYear() ? 29 : 28;
default:
return 30;
}
}
};
class Day{
public:
uint8_t d;
Day(){
d = 1;
}
};
Year y;
Month m;
Day d;
Date& operator++(){
uint8_t maxDay = m.getDayCount(y);
d.d++;
if (d.d > maxDay){
d.d = 1;
m.m++;
if (m.m > 12){
m.m = 1;
y.y++;
}
}
return *this;
}
bool equal(Date _d){
return ((this->y.y == _d.y.y) && (this->m.m == _d.m.m) && (this->d.d == _d.d.d));
}
friend Date& operator >> (Date& _date, uint8_t& c){
Date date;
c = 0;
while (!date.equal(_date)){
date++;
c++;
}
return _date;
}
friend Date& operator << (Date& _date, uint8_t c){
Date date;
while (c--){
date++;
}
_date.y.y = date.y.y;
_date.m.m = date.m.m;
_date.d.d = date.d.d;
return _date;
}
void debug(){
printf("=[%d]=[%d]=[%d]=\n", this->y.y, this->m.m, this->d.d);
}
};
void testForTimestamp(void){
Date date;
date.debug();
date << 100;
date.debug();
uint8_t c = 0;
date >> c;
printf("=[%d]=\n", c);
}
Demo Result
=[1900]=[1]=[1]=
=[1900]=[4]=[11]=
=[100]=
Summary
Point1 首先在定义年月日三个子类时注意不要让两者之间产生过多的联系,让Date这个类来统筹整个数据,过多的联系会让整个程序复杂且不利于维护
Point2 在类中封装自己的方法,在使用类对象时做到尽量简化
Point3 对于移位运算符的重载,这里这里类比于cout函数配合该操作符的使用,即将其看做一个数据的流向,这里我们可以看到重载的两个方法,一个是将Date类中的数据流出为偏移天数,另一个是输入偏移天数来更改Date数据