C++日期类(Date)实现的示例代码

目录
  • 类的定义
  • 确定某年某月有多少天
  • 构造函数
  • 打印日期
  • 日期+=天数
  • 日期+天数
  • 日期-=天数
  • 日期-天数
  • 前置++
  • 后置++
  • 后置–
  • 前置–
  • >运算符重载
  • ==运算符重载
  • >=运算符重载
  • <运算符重载
  • <=运算符重载
  • !=运算符重载
  • 计算两个日期之间的间隔天数,日期减去日期

类的定义

#pragma once
#include < iostream>
using std::cout;
using std::cin;
using std::endl;
class Date
{
public:
	// 获取某年某月的天数
	int GetMonthDay(int year, int month);
	// 全缺省的构造函数
	Date(int year = 0, int month = 1, int day = 1);
	void Print();
    //析构,拷贝构造,赋值重载函数可以不用写,默认生成的就够用
	//日期+=天数
	Date& operator+=(int day);

	// 日+天数
	Date operator+(int day);

	// 日期-天数
	Date operator-(int day);

	// 日期-=天数
	Date& operator-=(int day);

	// 前置++
	Date& operator++();

	// 后置++
	Date operator++(int);

	//后置--
	Date operator--(int);

	// 前置--
	Date& operator--();

	// >运算符重载
	bool operator>(const Date& d);

	// ==运算符重载
	bool operator==(const Date& d);

	// >=运算符重载
	bool operator >= (const Date& d);

	// <运算符重载
	bool operator < (const Date& d);

	// <=运算符重载
	bool operator <= (const Date& d);

	// !=运算符重载
	bool operator != (const Date& d);

	// 日期-日期 返回天数
	int operator-(const Date& d);

private:
	int _year;
	int _month;
	int _day;
};

确定某年某月有多少天

//因为闰年和平年二月份的天数不一样,随便加加减减会有问题,这个函数可以根据闰年和平年给出对应的天数
//因为后面需要频繁调用它,设置成内联函数
inline int Date::GetMonthDay(int year, int month) {
    //设置成静态变量,不用每次调用这个函数都开辟一个数组
    static int arr[13] = {0,31,28,31,30,31,30,31,31,30,31, 30, 31};
    int day = arr[month];
    if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
        day = 29;
    return day;
}

构造函数

Date::Date(int year, int month, int day) {
    //防止给的日期有错误
    if (year >= 0 && month > 0 && month < 13
        && day >0 && day <= GetMonthDay(year, month)) {
        _year = year;
        _month = month;
        _day = day;
    }
    else {
        cout << "非法日期" << endl;
        cout << year << "年" << month << "月" << day << "日" << endl;
    }
}

打印日期

void Date::Print() {
    cout << _year << "年" << _month << "月" << _day << "日" << endl;
}

日期+=天数

Date& Date::operator+=(int day) {
    if (day < 0){
        *this -= (-day);
    }
    else {
        _day += day;
        //如果天数大于月份对应的最大天数,就先减去这个月天数,然后月份++,然后再判断月份对应的天数对不对,往复循环
        while (_day > GetMonthDay(_year, _month)) {
            _day -= GetMonthDay(_year, _month);
            ++_month;
            if (_month > 12) {
                ++_year;
                _month = 1;
            }
        }
        //如果是传值返回的话传的是他的一个拷贝临时变量,又需要调用拷贝构造函数,因为出了函数作用域对象还在,所以传引用更好。
    }
    return *this;
}

日期+天数

Date Date::operator+(int day) {
    Date ret(*this);
    //复用operator+=函数
    ret += day;
    //ret是一个局部变量,出了作用域就销毁了,传不了引用
    return ret;
}

日期-=天数

Date& Date::operator-=(int day) {
    if (day < 0) {
        *this += (-day);
    }
    else {
        _day -= day;
        while (_day <= 0) {
            --_month;
            if (_month < 1) {
                --_year;
                _month = 12;
            }
            _day += GetMonthDay(_year, _month);
        }
    }
    return *this;
}

日期-天数

Date Date::operator-(int day) {
    Date ret = *this;
    ret -= day;
    return ret;
}

前置++

//返回的是++后的值,可以复用+=函数,逻辑是一样的,把day换成1即可
Date& Date::operator++() {
    *this += 1;
    return *this;
}

后置++

//返回的是++前的值,不能传引用返回
//为了和前置++赋值重载函数构成函数重载,需要加个int ,不需要传实参,因为没用,如果不加参数那么前置++和后置++函数就一样了,们在进行前置++或者后置++操作时,编译器就不知道调用哪一个了
Date Date::operator++(int) {
    Date ret(*this);
    *this += 1;
    return ret;
}

后置–

//返回原对象,然后对象再--
Date Date::operator--(int) {
    Date ret = *this;
    *this -= 1;
    return ret;
}

前置–

返回--后的对象

Date& Date::operator--() {
    *this -= 1;
    return *this;
}

>运算符重载

d1 > d2  -> d1.operator>(&d1, d2)
bool Date::operator>(const Date& d) {
    if (_year >= d._year)
    {
        if (_year > d._year)
            return true;
        else {
            if (_month >= d._month) {
                if (_month > d._month)
                    return true;
                else {
                    if (_day > d._day)
                        return true;
                }
            }
        }
    }
    return false;
}

==运算符重载

bool Date::operator==(const Date& d)
{
    return _year == d._year && _month == d._month && _day == d._day;
}

>=运算符重载

bool Date::operator >= (const Date& d)
{
    return *this > d || *this == d;
}

<运算符重载

bool Date::operator < (const Date& d)
{
    return !(*this >= d);
}

<=运算符重载

bool Date::operator <= (const Date& d)
{
    return !(*this > d);
}

!=运算符重载

bool Date::operator != (const Date& d)
{
    return !(*this == d);
}

计算两个日期之间的间隔天数,日期减去日期

int Date::operator-(const Date& d) {
    Date min = *this;
    Date max = d;
    int flag = -1;
    int daycount = 0;
    if (*this > d) {
        min = d;
        max = *this;
        flag = 1;
    }
    while (min != max) {
        ++min;
        daycount++;
    }
    return flag * daycount;
}

到此这篇关于C++日期类(Date)实现的示例代码的文章就介绍到这了,更多相关C++日期类内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现日期类(Date)

    本文实例为大家分享了C++实现日期类的具体代码,供大家参考,具体内容如下 #include<iostream> #include<stdlib.h> using namespace std; class Date { public: //构造函数 Date(int year = 1900, int month = 1, int day = 1) :_year(year) , _month(month) , _day(day) { if (!IsInvalidDate(_year,

  • C++逐步介绍日期类的使用

    目录 头文件 详细步骤 第一步 第二步 总代码 我们今天实现一个简单的计算日期 我们这里先给出头文件,后面一个一个解释 头文件 #pragma once #include<iostream> using std::cout; using std::endl; using std::cin; class Date { public: //定义构造函数 Date(int year = 1900, int month = 1, int day = 1); //打印日期 void Print() {

  • C++类与对象之日期类的实现

    目录 1. 实现前的铺垫 2. 日期类的实现 2.1 日期+=天数 2.2 日期-=天数 2.3 日期-天数 2.4 日期+天数 2.5 前置++ 2.6 后置++ 2.7 前置– 2.8 后置– 2.9 >运算符重载 2.10 ==运算符重载 2.11 >=运算符重载 2.12 <运算符重载 2.13 <=运算符重载 2.14 !=运算符重载 2.15 日期-日期 返回天数 2.16 输出 1. 实现前的铺垫 在实现前,我们要先把类写好,类中包含成员函数和成员变量. 对于日期类来

  • C++实现日期类(Date类)的方法

    如下所示: #include<iostream> using namespace std; class Date { public: Date(int year = 1900, int month = 1, int day = 1) //构造 :_year(year) , _month(month) , _day(day) { if (!isInvalidDate(_year, _month, _day)) { _year = 1900; _month = 1; _day = 1; } } D

  • C++日期类(Date)实现的示例代码

    目录 类的定义 确定某年某月有多少天 构造函数 打印日期 日期+=天数 日期+天数 日期-=天数 日期-天数 前置++ 后置++ 后置– 前置– >运算符重载 ==运算符重载 >=运算符重载 <运算符重载 <=运算符重载 !=运算符重载 计算两个日期之间的间隔天数,日期减去日期 类的定义 #pragma once #include < iostream> using std::cout; using std::cin; using std::endl; class Da

  • sql通过日期判断年龄函数的示例代码

    定义函数: CREATE FUNCTION [dbo].[GetAge] ( @BirthDay nvarchar(20) --生日 ) RETURNS varchar(20) AS BEGIN if(@BirthDay is NUlL or @BirthDay='') return ''; -- Declare the return variable here DECLARE @age varchar(20) DECLARE @years int DECLARE @months int DEC

  • MySQL 日期时间加减的示例代码

    目录 1.MySQL加减某个时间间隔 2.日期相减 最近在复习MySQL,正好看到了MySQL 日期时间,本文就给自己留个笔记,顺便分享给大家 now (); 当前具体的日期和时间 curdate (); 当前日期 curtime(); 当前时间 1.MySQL加减某个时间间隔 设置当前日期变量 set @dt = now(); //设置当前日期 select @dt; //查询变量值 加减某个时间间隔函数date_add()与date_sub() date_add('某个日期时间',inter

  • 新手小白学JAVA 日期类Date SimpleDateFormat Calendar(入门)

    目录 1. Date日期类 1.1 Date的构造函数 1.2 Date的构造函数练习 1.3 Date的常用方法练习 2. SimpleDateFormat 2.1 常用构造函数 2.2 日期转换格式工具类练习 2.3 日期转换综合练习 3.Calendar日历类 3.1 概念 3.2 常用方法 3.3 入门案例 3.4 巩固案例 1. Date日期类 类 Date 表示一个特定的瞬间,精确到毫秒 1.1 Date的构造函数 Date() 分配一个 Date 对象,以表示分配它的时间(精确到毫

  • Java利用File类创建文件的示例代码

    只需要调用该类的一个方法createNewFile(),但是在实际操作中需要注意一些事项,如判断文件是否存在,以及如何向新建文件中写入数据等. import java.io.*; public class CreateNewFile{ //该方法用于创建文件,参数分别是文件路径和文件名.文件内容,如:myfile.doc HelloJava! public void createNewFile(String fileDirectoryAndName,String fileContent){ tr

  • JavaScript日期对象(Date)基本用法示例

    本文实例讲述了JavaScript日期对象(Date)基本用法.分享给大家供大家参考,具体如下: 1.获取当前日期: document.write("Current time: "+new Date()); 2.获取时间戳(毫秒): document.write(new Date().getTime()); 3.设置年月日(年为必选,月日为可选): var d = new Date(); d.setFullYear(2016,3,16) document.write(d); docum

  • C++时间戳转换成日期时间的步骤和示例代码

    因工作需要,经常跟时间戳打交道,但是因为它仅仅是一个数字,我们很难直接看出它有什么意义,或两个时间戳之间究竟差了多长的间隔.于是从MSDN for Visual Studio6上找到了时间戳转换成日期时间的算法.本文除介绍这一算法外,还提供一个示例代码. 1.将时间戳转换成一串32比特的二进制数.有些数字转换之后不够32位,则在前面补充0.这可通过windows自带的计算器完成.比如481522543转换成 0001 1100 1011 0011 0111 0011 0110 1111 2.根据

  • java8 时间日期的使用与格式化示例代码详解

    目录 LocalDate LocalTime LocalDateTime Instant Duration Period ZoneId 时间与字符串之间的转化 与旧Date API的转换 LocalDate // 日期 LocalDate localDate = LocalDate.now(); System.out.println(localDate); // yyyy-MM-dd System.out.println(localDate.getYear()); // 年 System.out

  • ASP.NET JSON字符串与实体类的互转换示例代码

    还是先封装一个类吧! 这个类网上都可以找到的!有个这个类,一切都将变得简单了,哈哈. 复制代码 代码如下: using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Runtime.Serialization.Json;using System.ServiceModel.Web;///记得引用这个命名空间using System.IO;using System.Tex

随机推荐