参照正规项目的写法,我们分成三个文件:
- Date.h——类的实现和函数声明
- Date.cpp——函数实现
- 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</

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

被折叠的 条评论
为什么被折叠?



