C++初阶(4)——Date日期类的具体实现

这篇博客介绍了如何使用C++实现一个日期类,包括构造函数、打印方法、日期的加减运算符重载、前缀后缀递增递减操作符以及比较运算符的实现。同时,提到了内联函数在获取每月天数中的应用,确保了日期的合法性。此外,还强调了常成员函数的使用以及代码复用的重要性。

参照正规项目的写法,我们分成三个文件:

  1. Date.h——类的实现和函数声明
  2. Date.cpp——函数实现
  3. test.cpp——测试用例

我们主要实现Date.h和Date.cpp,test.cpp读者可以实际需要自行实现

Date.h

#pragma once
#include<iostream>

//正规的项目写法中,只展开几个常用的函数,不展开整个命名空间
using std::cout;
using std::endl;
using std::cin;
 //本类中成员变量都是内置类型,因此析构,拷贝构造,赋值重载都可以不用写 
class Date
{
   
   
public:
	//1.构造函数
	Date(int year, int month , int day );
	
	//2.打印
	void Print() const;
	
	//3.重载+=
	Date& operator+=(int day);
	
	//4.重载+
	Date operator+(int day);
	
	//5.重载-=
	Date& operator-=(int day);
	
	//6.重载-(日期减int)
	Date operator-(int day);
	
	//7.重载前置++与后置++
	Date& operator++();
	Date operator++(int);

	//8.重载前置--与后置--
	Date& operator--();
	Date operator--(int);

	//9.重载各比较运算符
	bool operator>(const Date& d);
	bool operator==(const Date& d) const;
	bool operator>=(const Date& d);
	bool operator!=(const Date& d);
	bool operator<(const Date& d);
	bool operator<=(const Date& d);
	 
	//10.重载-(日期减日期)
	int operator-(const Date& d);
private:
	int _year;
	int _month;
	int _day;
};

Date.cpp

先编写一个提取每月天数的函数GetMonthDay,这在后面的多个函数中都有调用,故设计成内联。内联函数不支持定义和声明分离,故Date.h中没有声明该函数

#include "Date.h"

//每生成一个对象就要调用一次,故设置成内联
inline int GetMonthDay(int year,int month)
{
   
   
	//第一个给0是为了然后给月份和数组下标一一对应
	static</
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值