【C++】日期类的实现

简介: 【C++】日期类的实现

👉前言👈


在前三篇的类和对象的博客中,本人已经讲解了类和对象的全部知识点。这些知识点都是通过我们比较熟悉的日期类Date、栈Stack和队列MyQueue来讲解的,那么本篇文章就将日期类的实现总结一下。


👉Date.h👈


头文件Date.h里主要放着头文件的包含、类型的声明、函数的声明。日期类主要需要实现的函数有构造函数(注:析构函数和拷贝构造函数不需要自己写,编译器默认生成的就够用了)、运算符重载、计算日期是一年中的第几天以及将一年中的第几天转换成日期。


主要:在类中定义的成员函数会被当做内联函数处理,我们可以将被频繁调用的小函数在类中定义,不经常被调用的函数在类外定义。因为流插入<<和流提取>>的重载在类中定义,可读性不高,不符合使用习惯,所以我们利用友元将这两个函数重载在类外定义。


#pragma once
#include <iostream>
using namespace std;
class Date
{
public:
  // 友元声明(类的任意位置)
  friend ostream& operator<<(ostream& out, const Date& d);
  friend istream& operator>>(istream& in, Date& d);
  int GetMonthDay(int year, int month)
  {
    static int monthDayArray[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
    if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
    {
      return 29;
    }
    else
    {
      return monthDayArray[month];
    }
  }
  Date(int year = 1, int month = 1, int day = 1)
  {
    _year = year;
    _month = month;
    _day = day;
    // 检查日期是否合法
    if (!(year >= 1
      && (month >= 1 && month <= 12)
      && (day >= 1 && day <= GetMonthDay(year, month))))
    {
      cout << "非法日期" << endl;
    }
  }
  void Print() const
  {
    cout << _year << '/' << _month << '/' << _day << endl;
  }
  bool operator==(const Date& d) const;
  // d1 > d2
  bool operator>(const Date& d) const;
  // d1 >= d2
  bool operator>=(const Date& d) const;
  bool operator<=(const Date& d) const;
  bool operator<(const Date& d) const;
  bool operator!=(const Date& d) const;
  // d1 += 100
  Date& operator+=(int day);
  // d1 + 100
  Date operator+(int day) const;
  // d1 -= 100
  Date& operator-=(int day);
  // d1 - 100
  Date operator-(int day) const;
  // 前置
  Date& operator++();
  // 后置
  Date operator++(int);
  // 前置
  Date& operator--();
  // 后置
  Date operator--(int);
  // d1 - d2
  int operator-(const Date& d) const;
  Date* operator&()
  {
    return this;
    // 要求这个类的对象不让取地址
    //return nullptr;
  }
  const Date* operator&() const
  {
    return this;
    //return nullptr; 
  }
  // 计算日期是一年中的第几天
  int DayOfYear() const;
private:
  int _year;
  int _month;
  int _day;
};
// operator<<(cout, d1) cout<<d1
inline ostream& operator<<(ostream& out, const Date& d)
{
  out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
  return out;
}
// cin >> d1  operator(cin, d1)
inline istream& operator>>(istream& in, Date& d)
{
  in >> d._year >> d._month >> d._day;
  return in;
}
// 将一年中的第几天转换成日期
void DaysToDate();


👉Date.cpp👈


日期类需要实现的函数大多数是运算符重载,这些运算符重载在类和对象(中)这篇文章里讲过。如果还有不懂,可以点击跳转学习一下。运算符重载最重要的就是学会赋用已经写好的运算符重载,这样可以达到事半功倍的效果。


#include "Date.h"
bool Date::operator==(const Date& d) const
{
  return _year == d._year
    && _month == d._month
    && _day == d._day;
}
bool Date::operator>(const Date& d) const
{
  if (_year > d._year)
  {
    return true;
  }
  else if (_year == d._year && _month > d._month)
  {
    return true;
  }
  else if (_year == d._year && _month == d._month && _day > d._day)
  {
    return true;
  }
  return false;
}
bool Date::operator>=(const Date& d) const
{
  return *this > d || *this == d;
}
bool Date::operator<=(const Date& d) const
{
  return !(*this > d);
}
bool Date::operator<(const Date& d) const
{
  return !(*this >= d);
}
bool Date::operator!=(const Date& d) const
{
  return !(*this == d);
}
Date& Date::operator+=(int day)
{
  if (day < 0)
  {
    return *this -= -day;
  }
  _day += day;
  while (_day > GetMonthDay(_year, _month))
  {
    _day -= GetMonthDay(_year, _month);
    ++_month;
    if (_month == 13)
    {
      ++_year;
      _month = 1;
    }
  }
  return *this;
}
Date Date::operator+(int day) const
{
  Date ret(*this);
  ret += day;
  return ret;
}
Date& Date::operator-=(int day)
{
  if (day < 0)
  {
    return *this += -day;
  }
  _day -= day;
  while (_day <= 0)
  {
    --_month;
    if (_month == 0)
    {
      --_year;
      _month = 12;
    }
    _day += GetMonthDay(_year, _month);
  }
  return *this;
}
Date Date::operator-(int day) const
{
  Date ret(*this);
  ret -= day;
  return ret;
}
// 前置
Date& Date::operator++()
{
  *this += 1;
  return *this;
}
// 后置 -- 多一个int参数主要是为了根前置区分
// 构成函数重载
Date Date::operator++(int)
{
  Date tmp(*this);
  *this += 1;
  return tmp;
}
// 前置
Date& Date::operator--()
{
  *this -= 1;
  return *this;
}
// 后置
Date Date::operator--(int)
{
  Date tmp(*this);
  *this -= 1;
  return tmp;
}
// 日期差值 d1 - d2
int Date::operator-(const Date& d) const
{
  Date max = *this;
  Date min = d;
  int flag = 1;
  if (*this < d)
  {
    max = d;
    min = *this;
    flag = -1;
  }
  int n = 0;
  while (min != max)
  {
    ++n;
    ++min;
  }
  return n * flag;
}
int Date::DayOfYear() const
{
  static int Day[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
  int n = Day[_month - 1] + _day;
  if (_month > 2 && ((_year % 4 == 0 && _year % 100 != 0) || (_year % 400 == 0)))
    ++n;
  return n;
}
void DaysToDate()
{
  int year = 0;
  int days = 0;
  cin >> year >> days;
  static int Day[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  if (((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
    && (days > 60))
  {
    --days;
  }
  int month = 1;
  while (days > Day[month])
  {
    days -= Day[month];
    month++;
  }
  printf("%04d-%02d-%02d\n", year, month, days);
}


计算日期是一年中的第几天


  • 定义一个数组,数组里存储的是到这个月的月底是该年的第几天
  • 计算日期是一年中的第几天n = Day[_month - 1] + _day
  • 如果月份month大于 2 且年份year为闰年,则n++



int Date::DayOfYear() const
{
  static int Day[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
  int n = Day[_month - 1] + _day;
  if (_month > 2 && ((_year % 4 == 0 && _year % 100 != 0) || (_year % 400 == 0)))
    ++n;
  return n;
}


将一年中的第几天转换成日期


定义一个数组,数组中存储着平年每个月份的天数

如果年份year为闰年且天数days大于 60,则--days

定义月份month = 1,当days > Day[month]时,进入 while 循环,days -= Day[month] month++;当 while 循环结束时,就能求出month和days

注:1 <= days <= 366


void DaysToDate()
{
  int year = 0;
  int days = 0;
  cin >> year >> days;
  static int Day[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  if (((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
    && (days > 60))
  {
    --days;
  }
  int month = 1;
  while (days > Day[month])
  {
    days -= Day[month];
    month++;
  }
  printf("%04d-%02d-%02d\n", year, month, days);
}


👉Test.cpp👈


Test.cpp源文件主要负责测试函数接口实现得是否正确。验证函数接口都正确后,就可以写过菜单来和用户交互了。不过,本人不太推荐写菜单,所以我就没有写菜单了。如果大家有需求的话,也可以自己写一写菜单。


#include "Date.h"
void TestDate1()
{
  Date d1(2022, 11, 14);
  Date d2(2022, 11, 15);
  cout << (d1 == d2) << endl;
  cout << (d1 > d2) << endl;
  cout << (d1 >= d2) << endl;
  cout << (d1 <= d2) << endl;
  cout << (d1 < d2) << endl;
  cout << (d1 != d2) << endl;
  cout << (d1 += 100);
  cout << (d2 -= 100);
  cout << d1.DayOfYear() << endl;
  DaysToDate();
}
int main()
{
  TestDate1();
  return 0;
}

15953c176a1340d8ad942586138f7152.png


98e330e36bcd427aa7a8b638431fcea6.png



看完本篇博客,大家可以做一下下面几道 OJ 题来巩固自己所学到的知识哦。




👉总结👈


本篇博客主要是对前三篇类和对象写的日期类的小总结,如果大家觉得有收获的话,可以点个三连支持一下!谢谢大家啦!💖💝❣️




















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