C++番外篇——日期类的实现

简介: C++番外篇——日期类的实现

前言

生活中,我们时不时会遇到算天数的问题:高考倒计时、考研倒计时、过年倒计时......

想解决这些问题无非就是实现一个年月日的计算器,那要怎么来实现呢?

下面就让我们来探究一下。

1.了解日期计算器的需求

1.1 表面需求

实现日期计算器无非有以下这些需求:

日期+天数得到新日期(原日期不变)

Date& operator+=(int day);

日期-天数得到新日期(原日期不变)

Date& operator-=(int day);

日期+天数,得到新日期(原日期改变)

Date operator+(int day);

日期-天数,得到新日期(原日期改变)

Date operator-(int day);

以及最常用的:两个日期相减,算天数

int operator-(const Date& d);

1.2 潜在需求

要想实现以上几个需求,我们还必须要存在判断两个日期是否相等的函数存在:

判断两个日期是否等于

bool operator==(const Date& x);

判断两个日期是否不等于

bool operator!=(const Date& x);

判断两个日期是否大于

bool operator>(const Date& x);

判断两个日期是否小于

bool operator<(const Date& x);

判断两个日期是否大于等于

bool operator>=(const Date& x);

判断两个日期是否小于等于

bool operator<=(const Date& x);

前置++ ,前置--

Date& operator++();
Date& operator--();

后置++,后置--

Date operator++(int);
Date operator--(int);

以及一个最重要的接口函数:判断大小月、闰平月

int GetMonthDay(int year, int month);

2. 需求实现

构造函数实现

Date::Date(int year, int month, int day)
{
  _year = year;
  _month = month;
  _day = day;
  if (_year < 1 || _month < 1 || _month>12 || _day<1 || _day>GetMonthDay(_year, _month))
  {
    //assert(false);//如果日期输入错误,暴力中断程序
    Print();
    cout << "日期错误" << endl;//如果日期输入错误,温柔地警告日期错误
  }
}

打印函数实现

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

接口函数,判断大小月、润平月函数实现

int Date::GetMonthDay(int year, int month)
{
  assert(year >= 1 && month >= 1 && month <= 12);//检查日期是否合法
 
  //定义一个数组存储12个月
  int arrmonth[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
 
  //如果是闰年2月,返回29天
  if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
  {
    return 29;
  }
 
  return arrmonth[month];
}

赋值运算符重载函数实现

判断两个日期是否等于、不等于、大于、小于、大于等于、小于等于

//赋值运算符重载函数实现
//d1==d2
bool Date::operator==(const Date& x)
{
  return _year == x._year && _month == x._month && _day == x._day;
}
//d1!=d2
bool Date::operator!=(const Date& x)
{
  return !(*this == x);//*this为d1,x为d2,这里相当于调用了operator==
}
//d1>d2
bool Date::operator>(const Date& x)
{
  if (_year > x._year)
  {
    return true;
  }
  else if (_year == x._year && _month > x._month)
  {
    return true;
  }
  else if (_year == x._year && _month == x._month && _day > x._day)
  {
    return true;
  }
  return false;
}
//d1<d2
bool Date::operator<(const Date& x)
{
  return !(*this >= x);//复用operator==和operator>
}
//d1>=d2
bool Date::operator>=(const Date& x)
{
  return *this == x || *this > x;//复用operator==和operator>
}
//d1<=d2
bool Date::operator<=(const Date& x)
{
  return !(*this > x);//复用operator>
}

运算符重载函数实现

日期+天数得到新日期实现(+=原日期不变)

//日期+天数得到新日期实现(+=原日期不变)
Date& Date::operator+=(int day)
{
  if (day < 0)//避免输入负数
  {
    return *this -= (-day);//这里operator+=与operator-=互相调用
  }
  _day += day;
  while (_day > GetMonthDay(_year, _month))//当_day<=一个月的天数时,终止循环
  {
    _day -= GetMonthDay(_year, _month);
    //每减过一个月的天数,month就+1
    ++_month;
    if (_month == 13)
    {
      _year++;
      _month = 1;
    }
  }
  return *this;
}

日期-天数得到新日期实现(-=原日期不变)

//日期-天数得到新日期实现(-=原日期不变)
Date& Date::operator-=(int day)
{
  if (day < 0)//避免输入负数
  {
    return *this += (-day);//这里operator+=与operator-=互相调用
  }
  _day -= day;
  while (_day <= 0)//当_day>0时,终止循环
  {
    --_month;//每进一次循环month就-1
    if (_month == 0)
    {
      --_year;
      _month = 12;
    }
    _day += GetMonthDay(_year, _month);//计算完year与month后,令day加这个月天数
  }
  return *this;
}

前置++与前置--重载

//前置++重载
Date& Date::operator++()
{
  *this += 1;//这里复用operator+=
  //前置++,先加后用,因此返回+1之后的日期
  //this出作用域未销毁,因此返回this的地址,以&做返回值
  return *this;
}
//前置--重载
Date& Date::operator--()
{
  *this -= 1;
  return *this;
}

后置++与后置--重载

//后置++重载
Date Date::operator++(int)
{
  Date tmp(*this);//创建临时变量tmp,调用拷贝构造,tmp拷贝this
  *this += 1;
  //后置++,先用后加,因此返回+1之前的tmp
  //tmp出作用域被销毁,因此直接返回tmp的值,无需用&
  return tmp;
}
//后置--重载
Date Date::operator--(int)
{
  Date tmp(*this);
  *this -= 1;
  return tmp;
}

日期+-天数,得到新日期

//日期+-天数,得到新日期,返回Date类型
Date Date::operator+(int day)
{
  Date tmp(*this);
  tmp += day;//复用operator+=
  return tmp;
}
Date Date::operator-(int day)
{
  Date tmp(*this); 
  tmp -= day;//复用operator -=
  return tmp;
}

倒计时,两个日期相减,算天数

//两个日期相减,算天数,返回int类型
int Date::operator-(const Date& x)
{
  // 假设左大右小
  int flag = 1;
  Date max = *this;
  Date min = x;
  // 假设错了,左小右大
  if (*this < x)
  { max = x;
    min = *this;
    flag = -1;
  }
  int n = 0;
  while (min != max)
  {
    ++min;
    ++n;
  }
  return n * flag;
}

3.测试

测试d1与d2相隔多少天

int main()
{
  Date d1(2002, 7, 12);
  d1.Print();
  Date d2(2002, 7, 7);
  d2.Print();
  //测试d1与d2相隔多少天
  int ret1 = d1 - d2;
  cout << ret1 << endl;
  return 0;
}

我的结果:

电脑结果:

测试d1+10000天是何年何月何日

int main()
{
  Date d1(2002, 7, 12);
  d1.Print();
  Date d2(2002, 7, 7);
  d2.Print();
  //测试d1+10000天是何年何月何日
  Date ret2 = d1 + 10000;
  ret2.Print();
  return 0;
}

我的结果:

电脑结果:

测试d1-10000天是何年何月何日

int main()
{
  Date d1(2002, 7, 12);
  d1.Print();
  Date d2(2002, 7, 7);
  d2.Print();
  //测试d1-10000天是何年何月何日
  Date ret3 = d1 - 10000;
  ret3.Print();
  return 0;
}

我的结果:

电脑结果:

测试前置++与后置++

int main()
{
  Date d1(2002, 7, 12);
  d1.Print();
  Date d2(2002, 7, 7);
  d2.Print();
  //测试前置++与后置++
  Date ret4 = ++d1;
  d1.Print();
  ret4.Print();
  cout << endl;
  Date ret5 = d1++;
  d1.Print();
  ret5.Print();
  return 0;
}

4. 源代码

Date.h

#pragma once
 
#include <iostream>
#include <assert.h>
 
using namespace std;
 
class Date
{
public:
  //构造函数(全缺省)
  Date(int year = 2002, int month = 7, int day = 7);
 
 
  //打印函数
  void Print();
 
 
  //判断大小月、闰平月
  int GetMonthDay(int year, int month);
 
 
  //赋值运算符重载函数
  //bool类型,判断两个日期是否等于、不等于、大于、小于、大于等于、小于等于
  bool operator==(const Date& x);
  bool operator!=(const Date& x);
  bool operator>(const Date& x);
  bool operator<(const Date& x);
  bool operator>=(const Date& x);
  bool operator<=(const Date& x);
 
 
  //运算符重载函数
  //日期+天数得到新日期(原日期不变)
  Date& operator+=(int day);
  //日期-天数得到新日期(原日期不变)
  Date& operator-=(int day);
  //前置++与后置++重载
  Date& operator++();
  Date operator++(int);
  //前置--与后置--重载
  Date& operator--();
  Date operator--(int);
  //日期+-天数,得到新日期,返回Date类型
  Date operator+(int day);
  Date operator-(int day);
  //两个日期相减,算天数,返回int类型
  int operator-(const Date& d);
 
  
private:
  int _year;
  int _month;
  int _day;
};

Date.cpp

#define _CRT_SECURE_NO_WARNINGS 1
#include "Date.h"
 
 
//构造函数实现
Date::Date(int year, int month, int day)
{
  _year = year;
  _month = month;
  _day = day;
  if (_year < 1 || _month < 1 || _month>12 || _day<1 || _day>GetMonthDay(_year, _month))
  {
    //assert(false);//如果日期输入错误,暴力中断程序
    Print();
    cout << "日期错误" << endl;//如果日期输入错误,温柔地警告日期错误
  }
}
 
 
//打印函数实现
void Date::Print()
{
  cout << _year << "-" << _month << "-" << _day << endl;
}
 
 
//判断大小月、润平月函数实现
int Date::GetMonthDay(int year, int month)
{
  assert(year >= 1 && month >= 1 && month <= 12);//检查日期是否合法
 
  //定义一个数组存储12个月
  int arrmonth[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
 
  //如果是闰年2月,返回29天
  if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
  {
    return 29;
  }
 
  return arrmonth[month];
}
 
 
//赋值运算符重载函数实现
//d1==d2
bool Date::operator==(const Date& x)
{
  return _year == x._year && _month == x._month && _day == x._day;
}
//d1!=d2
bool Date::operator!=(const Date& x)
{
  return !(*this == x);//*this为d1,x为d2,这里相当于调用了operator==
}
//d1>d2
bool Date::operator>(const Date& x)
{
  if (_year > x._year)
  {
    return true;
  }
  else if (_year == x._year && _month > x._month)
  {
    return true;
  }
  else if (_year == x._year && _month == x._month && _day > x._day)
  {
    return true;
  }
  return false;
}
//d1<d2
bool Date::operator<(const Date& x)
{
  return !(*this >= x);//复用operator==和operator>
}
//d1>=d2
bool Date::operator>=(const Date& x)
{
  return *this == x || *this > x;//复用operator==和operator>
}
//d1<=d2
bool Date::operator<=(const Date& x)
{
  return !(*this > x);//复用operator>
}
 
 
//运算符重载函数实现
//日期+天数得到新日期实现(+=原日期不变)
Date& Date::operator+=(int day)
{
  if (day < 0)//避免输入负数
  {
    return *this -= (-day);//这里operator+=与operator-=互相调用
  }
  _day += day;
  while (_day > GetMonthDay(_year, _month))//当_day<=一个月的天数时,终止循环
  {
    _day -= GetMonthDay(_year, _month);
    //每减过一个月的天数,month就+1
    ++_month;
    if (_month == 13)
    {
      _year++;
      _month = 1;
    }
  }
  return *this;
}
//日期-天数得到新日期实现(-=原日期不变)
Date& Date::operator-=(int day)
{
  if (day < 0)//避免输入正数
  {
    return *this += (-day);//这里operator+=与operator-=互相调用
  }
  _day -= day;
  while (_day <= 0)//当_day>0时,终止循环
  {
    --_month;//每进一次循环month就-1
    if (_month == 0)
    {
      --_year;
      _month = 12;
    }
    _day += GetMonthDay(_year, _month);//计算完year与month后,令day加这个月天数
  }
  return *this;
}
//前置++重载
Date& Date::operator++()
{
  *this += 1;//这里复用operator+=
  //前置++,先加后用,因此返回+1之后的日期
  //this出作用域未销毁,因此返回this的地址,以&做返回值
  return *this;
}
//后置++重载
Date Date::operator++(int)
{
  Date tmp(*this);//创建临时变量tmp,调用拷贝构造,tmp拷贝this
  *this += 1;
  //后置++,先用后加,因此返回+1之前的tmp
  //tmp出作用域被销毁,因此直接返回tmp的值,无需用&
  return tmp;
}
//前置--与后置--和++相同的道理
Date& Date::operator--()
{
  *this -= 1;
  return *this;
}
Date Date::operator--(int)
{
  Date tmp(*this);
  *this -= 1;
  return tmp;
}
//日期+-天数,得到新日期,返回Date类型
Date Date::operator+(int day)
{
  Date tmp(*this);
  tmp += day;//复用operator+=
  return tmp;
}
Date Date::operator-(int day)
{
  Date tmp(*this); 
  tmp -= day;//复用operator -=
  return tmp;
}
//两个日期相减,算天数,返回int类型
int Date::operator-(const Date& x)
{
  // 假设左大右小
  int flag = 1;
  Date max = *this;
  Date min = x;
  // 假设错了,左小右大
  if (*this < x)
  { max = x;
    min = *this;
    flag = -1;
  }
  int n = 0;
  while (min != max)
  {
    ++min;
    ++n;
  }
  return n * flag;
}

test.cpp

#define _CRT_SECURE_NO_WARNINGS 1
#include "Date.h"
 
int main()
{
  Date d1(2002, 7, 12);
  d1.Print();
  Date d2(2002, 7, 7);
  d2.Print();
  cout << endl;
 
  //测试d1与d2相隔多少天
  int ret1 = d1 - d2;
  cout << ret1 << endl;
  cout << endl;
 
  //测试d1+10000天是何年何月何日
  Date ret2 = d1 + 10000;
  ret2.Print();
  cout << endl;
 
  //测试d1-10000天是何年何月何日
  Date ret3 = d1 - 10000;
  ret3.Print();
  cout << endl;
 
  //测试前置++与后置++
  Date ret4 = ++d1;
  d1.Print();
  ret4.Print();
  cout << endl;
  Date ret5 = d1++;
  d1.Print();
  ret5.Print();
  return 0;
}
相关文章
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
544 12
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
280 0
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
455 0
|
编译器 C语言 C++
类和对象的简述(c++篇)
类和对象的简述(c++篇)
|
设计模式 安全 C++
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
282 16
|
编译器 C++
类和对象(中 )C++
本文详细讲解了C++中的默认成员函数,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载和取地址运算符重载等内容。重点分析了各函数的特点、使用场景及相互关系,如构造函数的主要任务是初始化对象,而非创建空间;析构函数用于清理资源;拷贝构造与赋值运算符的区别在于前者用于创建新对象,后者用于已存在的对象赋值。同时,文章还探讨了运算符重载的规则及其应用场景,并通过实例加深理解。最后强调,若类中存在资源管理,需显式定义拷贝构造和赋值运算符以避免浅拷贝问题。
|
存储 编译器 C++
类和对象(上)(C++)
本篇内容主要讲解了C++中类的相关知识,包括类的定义、实例化及this指针的作用。详细说明了类的定义格式、成员函数默认为inline、访问限定符(public、protected、private)的使用规则,以及class与struct的区别。同时分析了类实例化的概念,对象大小的计算规则和内存对齐原则。最后介绍了this指针的工作机制,解释了成员函数如何通过隐含的this指针区分不同对象的数据。这些知识点帮助我们更好地理解C++中类的封装性和对象的实现原理。
|
安全 C++
【c++】继承(继承的定义格式、赋值兼容转换、多继承、派生类默认成员函数规则、继承与友元、继承与静态成员)
本文深入探讨了C++中的继承机制,作为面向对象编程(OOP)的核心特性之一。继承通过允许派生类扩展基类的属性和方法,极大促进了代码复用,增强了代码的可维护性和可扩展性。文章详细介绍了继承的基本概念、定义格式、继承方式(public、protected、private)、赋值兼容转换、作用域问题、默认成员函数规则、继承与友元、静态成员、多继承及菱形继承问题,并对比了继承与组合的优缺点。最后总结指出,虽然继承提高了代码灵活性和复用率,但也带来了耦合度高的问题,建议在“has-a”和“is-a”关系同时存在时优先使用组合。
963 6
|
C++ 芯片
【C++面向对象——类与对象】Computer类(头歌实践教学平台习题)【合集】
声明一个简单的Computer类,含有数据成员芯片(cpu)、内存(ram)、光驱(cdrom)等等,以及两个公有成员函数run、stop。只能在类的内部访问。这是一种数据隐藏的机制,用于保护类的数据不被外部随意修改。根据提示,在右侧编辑器补充代码,平台会对你编写的代码进行测试。成员可以在派生类(继承该类的子类)中访问。成员,在类的外部不能直接访问。可以在类的外部直接访问。为了完成本关任务,你需要掌握。
375 19