【C++基础】实现日期类

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

👻内容专栏: C/C++编程

🐨本文概括: C++实现日期类

🐼本文作者: 阿四啊

🐸发布时间:2023.9.7

对于类的成员函数的声明和定义,我们在类和对象上讲到过,需要进行声明和定义分离。

一些需要使用的接口函数声明,我们放入到Date.h文件中
#include <iostream>
using namespace std;
class Date
{
public:
  //构造函数
  Date(int year = 1, int month = 1, int day = 1);
  //拷贝构造函数
  Date(const Date& d);
  //析构函数
  //~Date(); //日期类可以不写
  //打印日期
  void Print()const;
  //运算符重载
  bool operator<(const Date& d) const;
  bool operator==(const Date& d) const;
  bool operator<=(const Date& d) const;
  bool operator>(const Date& d) const;
  bool operator>=(const Date& d) const;
  bool operator!=(const Date& d) const;
  //赋值运算符重载
  Date& operator=(const Date& d);
  //日期+= 天数
  Date& operator+=(int day);
  //日期 + 天数
  Date operator+(int day) const;
  //日期 -= 天数
  Date& operator-=(int day);
  //日期 - 天数
  Date operator-(int day) const;
  //获取当月天数
  int GetMonthDay(int year, int month) const;
  //前置++
  Date& operator++();
  //后置++
  Date operator++(int);
  //前置--
  Date& operator--();
  //后置--
  Date operator--(int);
  //日期 - 日期 返回天数
  int operator-(const Date& d) const;
private:
  int _year;
  int _month;
  int _day;
};

🤗🤗下面,我们对一些日期接口函数的实现:

实现于Date.cpp文件中

一、构造函数、拷贝构造以及日期的打印

#include "date.h"
//构造函数
Date::Date(int year, int month, int day)
{
  _year = year;
  _month = month;
  _day = day;
  //检查日期是否合法
  if (month < 1 || month > 12 || day < 1 || day > GetMonthDay(year, month))
  {
    cout << "非法日期" << endl;
    //exit(-1);
  }
}
Date::Date(const Date& d)
{
  _year = d._year;
  _month = d._month;
  _day = d._day;
}
//Date::~Date()
//{
//  cout << "~Date()" << endl;
//}
void Date::Print() const
{
  cout << _year << "年" << _month << "月" << _day << "日" << endl;
}

二、赋值运算符重载函数

//赋值运算符重载
Date& Date::operator=(const Date& d)
{
  if (this != &d)
  {
    _year = d._year;
    _month = d._month;
    _day = d._day;
  }
  return *this;
}

三、运算符重载

比较运算符重载

我们写一个operator< 运算符重载函数和一个 operator== 运算符重载函数即可,其他直接复用就行。

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;
  }
  else
  {
    return false;
  }
}
bool Date::operator==(const Date& d) const
{
  return _year == d._year && _month == d._month
    && _day == d._day;
}
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) || (*this == d);
}
bool Date::operator!=(const Date& d) const
{
  return !(*this == d);
}

日期 ± 天数、日期 - 日期

获取当前月份的天数

首先我们需要写一个获取当月的天数GetMonthDay()函数,以便于后面用日期 ± 天数运算。

//获取当月天数
int Date::GetMonthDay(int year, int month) const
{
  static int MonthDayArray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  //判断是否为闰年(先判断是否为2月)
  if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 4 == 0)))
  {
    return 29;
  }
  return MonthDayArray[month];
}

日期 += 天数 与 日期 + 天数

//日期+= 天数
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 tmp(*this);
  tmp += day;
  return tmp;
}
日期+ 天数
//Date Date::operator+(int day)
//{
//  Date tmp(*this);
//  tmp._day += day;
//
//  while (tmp._day > GetMonthDay(tmp._year, tmp._month))
//  {
//    //月进位
//    tmp._day -= GetMonthDay(tmp._year, tmp._month);
//    tmp._month++;
//    if (tmp._month == 13)
//    {
//      tmp._year++;
//      tmp._month = 1;
//    }
//  }
//
//  return tmp;
//}
//
日期 += 天数
//Date& Date::operator+=(int day)
//{
//  *this = *this + day;
//  return *this;
//}

日期 -= 天数 与 日期 - 天数

我们知道了先写operator+=,再写operator+直接复用即可这种方法更优,所以我们日期减去天数也是实现operator-=,再实现operator-

//日期 -= 天数
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 tmp(*this);
  tmp -= day;
  return tmp;
}

自增 和 自减 重载

C++规定:前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载,后置++重载时多增加了一个int类型的参数,与前置++构成函数重载,以区分前置++

//前置++
Date& Date::operator++()
{
  *this += 1;
  //返回++之后的值
  return *this;
}
//后置++
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;//为1返回正数,-1返回负数
  int count = 0;//统计天数
  //不成立则交换
  if (*this < d)
  {
    max = d;
    min = *this;
    flag = -1;
  }
  //while(min < max)
  while (min != max)
  {
    min++;
    count++;
  }
  return count * flag;
}

四、全局函数实现流插入流提取

date.h 流插入流提取重载函数的声明
/*不能重载成成员函数,否则会导致参数不匹配,因为this指针永远占据第一个位置,无法进行流插入提取操作。*/
//流插入
ostream& operator<<(ostream& out, const Date& d);
//流提取
istream& operator>>(istream& in, Date& d);

如果重载成成员函数,那么成员函数的第一个参数永远是隐藏的this指针,成员函数中只能利用out << _year << _month << _day的顺序,但是在调用时, (d1为日期类对象)d1 << cout,只能这么写,虽然可以,但是很别扭,不符合使用习惯和价值。所以我们需要实现成全局函数才可以。

但是写成全局函数会访问类的成员变量,我们可以利用友元或者将成员变量封装成成员函数解决。

date.cpp 流插入流提取重载函数的实现
/*不能重载成成员函数,否则会导致参数匹配,因为this指针永远占据第一个位置,无法进行流插入提取操作。*/
//涉及访问私有成员变量可以利用友元,或者将成员变量封装成Get成员函数
//流插入
ostream& operator<<(ostream& out, const Date& d)
{
  out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
  return out;
}
//流提取
istream& operator>>(istream& in, Date& d)
{
  in >> d._year >> d._month >> d._day;
}
目录
打赏
0
0
0
0
1
分享
相关文章
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
43 0
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
110 0
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
112 12
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
96 16
类和对象(中 )C++
本文详细讲解了C++中的默认成员函数,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载和取地址运算符重载等内容。重点分析了各函数的特点、使用场景及相互关系,如构造函数的主要任务是初始化对象,而非创建空间;析构函数用于清理资源;拷贝构造与赋值运算符的区别在于前者用于创建新对象,后者用于已存在的对象赋值。同时,文章还探讨了运算符重载的规则及其应用场景,并通过实例加深理解。最后强调,若类中存在资源管理,需显式定义拷贝构造和赋值运算符以避免浅拷贝问题。
类和对象(上)(C++)
本篇内容主要讲解了C++中类的相关知识,包括类的定义、实例化及this指针的作用。详细说明了类的定义格式、成员函数默认为inline、访问限定符(public、protected、private)的使用规则,以及class与struct的区别。同时分析了类实例化的概念,对象大小的计算规则和内存对齐原则。最后介绍了this指针的工作机制,解释了成员函数如何通过隐含的this指针区分不同对象的数据。这些知识点帮助我们更好地理解C++中类的封装性和对象的实现原理。
|
4月前
|
【c++】继承(继承的定义格式、赋值兼容转换、多继承、派生类默认成员函数规则、继承与友元、继承与静态成员)
本文深入探讨了C++中的继承机制,作为面向对象编程(OOP)的核心特性之一。继承通过允许派生类扩展基类的属性和方法,极大促进了代码复用,增强了代码的可维护性和可扩展性。文章详细介绍了继承的基本概念、定义格式、继承方式(public、protected、private)、赋值兼容转换、作用域问题、默认成员函数规则、继承与友元、静态成员、多继承及菱形继承问题,并对比了继承与组合的优缺点。最后总结指出,虽然继承提高了代码灵活性和复用率,但也带来了耦合度高的问题,建议在“has-a”和“is-a”关系同时存在时优先使用组合。
234 6
类和对象(下)C++
本内容主要讲解C++中的初始化列表、类型转换、静态成员、友元、内部类、匿名对象及对象拷贝时的编译器优化。初始化列表用于成员变量定义初始化,尤其对引用、const及无默认构造函数的类类型变量至关重要。类型转换中,`explicit`可禁用隐式转换。静态成员属类而非对象,受访问限定符约束。内部类是独立类,可增强封装性。匿名对象生命周期短,常用于临时场景。编译器会优化对象拷贝以提高效率。最后,鼓励大家通过重复练习提升技能!
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问