【C++】Date(日期)类

本文介绍了一个日期类Date的设计与实现,包括构造函数、运算符重载等功能,并提供了代码示例进行测试验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、实现日期Date类。

二、代码演示

1、Date.h文件

2、Date.cpp文件


一、实现日期Date类。

1、实现Date类的带参构造函数、拷贝构造函数、拷贝赋值函数

2、实现Date类的+、-、++、--、==、>=等运算符的重载

二、代码演示

1、Date.h文件

实现类的成员变量定义和成员函数声明。

#pragma once
#include <iostream>
using namespace std;

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1);//默认构造函数
	Date(const Date& d);//拷贝构造函数
	Date& operator=(const Date& d);//拷贝赋值函数
	Date operator+(int days);//days天后日期
	Date operator-(int days);//days天前日期
	int operator-(const Date& d);//当前日期和d日期相差天数
	Date& operator++();//当前日期的后一天
	Date& operator--();//当前日期的前一天
	Date operator++(int);//某个日期的后一天
	Date operator--(int);//某个日期的前一天
	bool operator>(const Date& d)const;//判断当前日期是否大于d日期
	bool operator>=(const Date& d)const;//判断当前日期是否大于或等于d日期
	bool operator<(const Date& d)const;//判断当前日期是否小于d日期
	bool operator<=(const Date& d)const;//判断当前日期是否小于或等于d日期
	bool operator==(const Date& d)const;//判断当前日期是否等于d日期
	bool operator!=(const Date& d)const;//判断当前日期是否不等于d日期
	static bool leapYear(int);//判断是否为闰年
	bool endOfmonth(int)const;//判断是否为当月的最后一天
	void display();//显示日期
private:
	int _year;
	int _month;
	int _day;

	void dateAdd();//日期+1
	void dateMinus();//日期-1
};

2、Date.cpp文件

实现成员函数的定义及案例测试。


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值