[C++][Demo]Date类及移位操作符重载

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数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值