【C++从0到王者】第四站:日期类的实现

简介: 【C++从0到王者】第四站:日期类的实现


一、日期类的函数声明

在有了前面的类和对象的基础上,我们已经可以实现一个简单的日期类了,这个类它包括了日期的构造函数、日期的拷贝、日期的打印、日期的运算、包括两个日期的比较、相减、日期加减天数等运算。下面是日期类的函数声明

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
class Date
{
  //友元函数声明
  friend ostream& operator<<(ostream& out, const Date& d);
  friend istream& operator>>(istream& in, Date& d);
public:
  Date(int year = 1, int month = 1, int day = 1);
  void Print()
  {
    cout << _year << '-' << _month << '-' << _day << endl;
  }
  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);
  int GetMonthDay(int year, int month);
  Date& operator+=(int day);
  Date& operator-=(int day);
  Date operator+(int day);
  Date operator-(int day);
  Date& operator++();
  Date operator++(int);
  Date& operator--();
  Date operator--(int);
  int operator-(const Date& d);
private:
  int _year;
  int _month;
  int _day;
};
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);

二、日期类的实现

1.日期类的构造函数

如下代码所示,是日期类的构造函数,这里是函数的实现,由于是分文件,所以不能在这里写缺省参数,应该将缺省参数放在函数声明中。同时我们为了方便最好写一个获取某月的天数的函数,其中的天数的数组我们可以将他放到静态区。因为我们会频繁的调用它。

int Date::GetMonthDay(int year, int month)
{
  if (month <= 12 && month >= 1)
  {
    const static int ArrDay[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;
    }
    return ArrDay[month];
  }
  cout << "非法日期" << endl;
  return -1;
}
Date::Date(int year, int month, int day)
{
  if (month > 0 && month < 13
    && day>0 && day <= GetMonthDay(year, month))
  {
    _year = year;
    _month = month;
    _day = day;
  }
  else
  {
    cout << "非法日期" << endl;
    assert(false);
  }
}

2.日期类的析构与拷贝构造函数

这两个函数事实上是不需要我们去写的,因为我们的成员变量都是内置类型所以不需要写,使用编译器自己生成的就可以了

3.日期类的比较之d1<d2

这个运算符重载的功能是为了比较两个日期的大小,如果d1小于d2那么返回真,否则返回假。其中x是形参,他是d2的别名。且功能中并未涉及到修改d2,所以最好加上const,权限缩小。

d1<d2其实就会被编译器认为是d1.operator<(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;
}

4.日期类的比较之d1==d2

这个运算符重载的功能是比较d1是否等于d2,如果相等则返回真。

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

5.日期类的其他比较

一般来说,只要我们写出一个小于和等于,那么其他的比较函数都可以用这两个函数复用给实现出来。

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

6.日期类的+=和-=

首先我们需要判断的是day是否小于0,如果小于0的话,那么其实就可以相互复用。如果是大于0的话,就需要注意算法。先将day给加上去,然后如果day大于当月天数,那么就可以进位了。-=也是类似的思路。这里我们可以返回引用,因为我们返回的是原本的日期类,出了作用域,这个日期类还在

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 > 12)
    {
      _month -= 12;
      _year++;
    }
  }
  return *this;
}
Date& Date::operator-=(int day)
{
  if (day < 0)
  {
    return *this += -day;
  }
  _day -= day;
  while (_day <= 0)
  {
    _month--;
    if (_month <= 0)
    {
      _month += 12;
      _year--;
    }
    _day += GetMonthDay(_year, _month);
  }
  return *this;
}

7.日期类加减具体天数

事实上在这里我们可以直接复用+=和-=,但是由于加并不会改变原本的类,所以我们先使用拷贝构造一个,然后再返回即可,这里需要注意,我们必须得返回值而不是引用,因为出了作用域tmp就不在了

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

8.+复用+=还是+=复用+好

这里我们可能会注意到一个问题,是自己写一个+=,然后写+的时候直接复用+=好,还是自己先写一个+,然后写+=的时候直接复用+好。

其实是先写+=再让+复用+=效率要高一点,因为这样的话,首先直接使用+这个我们是不可避免的肯定会调用两次拷贝构造函数。而先写+=却不需要调用拷贝构造,如果后写+=的话,调用+的时候就会调用两次拷贝构造了。

9.前置++和后置++

这个从思路上来说比较容易实现,但是需要注意的是,如何区分前置++和后置++,再c++中,我们如果不带任何形参的话默认是前置++,如果带了一个形参的话,那就认为他是后置++。这里的实现直接复用+=即可

Date& Date::operator++()
{
  *this += 1;
  return *this;
}
Date Date::operator++(int)
{
  Date tmp = *this;
  *this += 1;
  return tmp;
}

10.前置–和后置–

这里的实现和前置++和后置++的思路基本一致

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

11.两个日期相减

这里仍然是运算符重载,但是和日期减某天这两个函数名相同,但参数类型不同,于是又构成了函数重载。这里我们采用循环计数的方法思路上比较容易实现。

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

12.流插入

这里需要注意的一点是,这个函数不可以写成成员函数。因为我们的Date对象默认占用第一个操作数。我们必须要更改操作数的位置,所以只能定义再全局中。但是这样我们就不可以使用私有的成员了,我们就有两种方案来处理,一种是在写一些获取每个成员值的函数,另外一种就是使用友元函数,你是我的朋友,所以可以来访问我的成员变量

//流插入不能写成成员函数
//因为Date对象默认占用第一个参数,就是做了左操作数
//写出来就是下面的样子,不符合我们的使用习惯
//d1<<cout;
ostream& operator<<(ostream& out, const Date& d)
{
  out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
  return out;
}

我们需要注意的是cout的类型是ostream,而且他不可以加上const,因为我们是在cout里面进行写入的。我们可以直接传别名过去使得效率更高。流插入运算符在库函数里事实上也是经历了大量的重载,才使得我们的cout可以自动识别类型。最后为了可以实现连续流插入,我们需要返回out

13.流提取

这个运算符与cout类似,我们也是必须使用友元函数进行声明。注意的是,这里的in和d都不可以加上const,因为他们都会被修改。最后为了连续的流提取,我们需要返回in

istream& operator>>(istream& in, Date& d)
{
  int year, month, day;
  in >> year >> month >> day;
  if (month > 0 && month < 13
    && day>0 && day <= d.GetMonthDay(year, month))
  {
    d._year = year;
    d._month = month;
    d._day = day;
  }
  else
  {
    cout << "非法日期" << endl;
    assert(false);
  }
  return in;
}

三、日期类的完整代码

Date.h

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
class Date
{
  //友元函数声明
  friend ostream& operator<<(ostream& out, const Date& d);
  friend istream& operator>>(istream& in, Date& d);
public:
  Date(int year = 1, int month = 1, int day = 1);
  void Print()
  {
    cout << _year << '-' << _month << '-' << _day << endl;
  }
  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);
  int GetMonthDay(int year, int month);
  Date& operator+=(int day);
  Date& operator-=(int day);
  Date operator+(int day);
  Date operator-(int day);
  Date& operator++();
  Date operator++(int);
  Date& operator--();
  Date operator--(int);
  int operator-(const Date& d);
private:
  int _year;
  int _month;
  int _day;
};
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);

Date.cpp

#define _CRT_SECURE_NO_WARNINGS 1
#include"Date.h"
Date::Date(int year, int month, int day)
{
  if (month > 0 && month < 13
    && day>0 && day <= GetMonthDay(year, month))
  {
    _year = year;
    _month = month;
    _day = day;
  }
  else
  {
    cout << "非法日期" << endl;
    assert(false);
  }
}
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;
}
bool Date::operator==(const Date& x)
{
  return (_year == x._year) &&
       (_month == x._month) &&
       (_day == x._day);
}
bool Date::operator<=(const Date& x)
{
  return (*this < x) || (*this == x);
}
bool Date::operator>(const Date& x)
{
  return !(*this <= x);
}
bool Date::operator>=(const Date& x)
{
  return !(*this < x);
}
bool Date::operator!=(const Date& x)
{
  return !(*this == x);
}
int Date::GetMonthDay(int year, int month)
{
  if (month <= 12 && month >= 1)
  {
    const static int ArrDay[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;
    }
    return ArrDay[month];
  }
  cout << "非法日期" << endl;
  return -1;
}
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 > 12)
    {
      _month -= 12;
      _year++;
    }
  }
  return *this;
}
Date& Date::operator-=(int day)
{
  if (day < 0)
  {
    return *this += -day;
  }
  _day -= day;
  while (_day <= 0)
  {
    _month--;
    if (_month <= 0)
    {
      _month += 12;
      _year--;
    }
    _day += GetMonthDay(_year, _month);
  }
  return *this;
}
Date Date::operator+(int day)
{
  Date tmp = *this;
  return tmp += day;
}
Date Date::operator-(int day)
{
  Date tmp = *this;
  return tmp -= day;
}
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;
}
int Date::operator-(const Date& d)
{
  Date max = *this;
  Date min = d;
  int flag = 1;
  if (max < min)
  {
    max = d;
    min = *this;
    flag = -1;
  }
  int n = 0;
  while (max != min)
  {
    min++;
    n++;
  }
  return flag * n;
}
//流插入不能写成成员函数
//因为Date对象默认占用第一个参数,就是做了左操作数
//写出来就是下面的样子,不符合我们的使用习惯
//d1<<cout;
ostream& operator<<(ostream& out, const Date& d)
{
  out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
  return out;
}
istream& operator>>(istream& in, Date& d)
{
  int year, month, day;
  in >> year >> month >> day;
  if (month > 0 && month < 13
    && day>0 && day <= d.GetMonthDay(year, month))
  {
    d._year = year;
    d._month = month;
    d._day = day;
  }
  else
  {
    cout << "非法日期" << endl;
    assert(false);
  }
  return in;
}

Test.cpp

#define _CRT_SECURE_NO_WARNINGS 1
#include"Date.h"
void TestDate1()
{
  Date d1;
  Date d2(2023, 5, 13);
  d1.Print();
  d2.Print();
  cout << (d1 < d2) << endl;
  cout << (d1 == d2) << endl;
  cout << (d1 > d2) << endl;
  cout << (d1 <= d2) << endl;
  d2 += 200;
  d2.Print();
  Date d3 = d2;
  d3 -= 200;
  d3.Print();
  d1 = d3 + 200;
  d1.Print();
}
void TestDate2()
{
  Date d1(2023, 5, 13);
  d1 -= -100;
  d1.Print();
  d1 += -100;
  d1.Print();
}
void TestDate3()
{
  Date d1(2023, 5, 13);
  Date ret1 = d1--;
  ret1.Print();
  Date ret2 = --d1;
  ret2.Print();
}
void TestDate4()
{
  Date d1(2023, 5, 13);
  Date d2(2049, 6, 13);
  cout << (d2 - d1) << endl;
  cout << d1 << d2;
  cin >> d2 >> d1;
  cout << d2 << d1;
}
void TestDate5()
{
  //Date d1(2022, 13, 1);
  Date d1;
  cin >> d1;
}
int main()
{
  TestDate5();
  return 0;
}

好了,本期内容就到这里了

如果对你有帮助的话不要忘记点赞加收藏哦

相关文章
|
14天前
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
16天前
|
编译器 C语言 C++
类和对象的简述(c++篇)
类和对象的简述(c++篇)
|
14天前
|
安全 编译器 C语言
【C++篇】深度解析类与对象(中)
在上一篇博客中,我们学习了C++类与对象的基础内容。这一次,我们将深入探讨C++类的关键特性,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载、以及取地址运算符的重载。这些内容是理解面向对象编程的关键,也帮助我们更好地掌握C++内存管理的细节和编码的高级技巧。
|
14天前
|
存储 程序员 C语言
【C++篇】深度解析类与对象(上)
在C++中,类和对象是面向对象编程的基础组成部分。通过类,程序员可以对现实世界的实体进行模拟和抽象。类的基本概念包括成员变量、成员函数、访问控制等。本篇博客将介绍C++类与对象的基础知识,为后续学习打下良好的基础。
|
2月前
|
C++ 芯片
【C++面向对象——类与对象】Computer类(头歌实践教学平台习题)【合集】
声明一个简单的Computer类,含有数据成员芯片(cpu)、内存(ram)、光驱(cdrom)等等,以及两个公有成员函数run、stop。只能在类的内部访问。这是一种数据隐藏的机制,用于保护类的数据不被外部随意修改。根据提示,在右侧编辑器补充代码,平台会对你编写的代码进行测试。成员可以在派生类(继承该类的子类)中访问。成员,在类的外部不能直接访问。可以在类的外部直接访问。为了完成本关任务,你需要掌握。
73 19
|
2月前
|
存储 编译器 数据安全/隐私保护
【C++面向对象——类与对象】CPU类(头歌实践教学平台习题)【合集】
声明一个CPU类,包含等级(rank)、频率(frequency)、电压(voltage)等属性,以及两个公有成员函数run、stop。根据提示,在右侧编辑器补充代码,平台会对你编写的代码进行测试。​ 相关知识 类的声明和使用。 类的声明和对象的声明。 构造函数和析构函数的执行。 一、类的声明和使用 1.类的声明基础 在C++中,类是创建对象的蓝图。类的声明定义了类的成员,包括数据成员(变量)和成员函数(方法)。一个简单的类声明示例如下: classMyClass{ public: int
60 13
|
2月前
|
编译器 数据安全/隐私保护 C++
【C++面向对象——继承与派生】派生类的应用(头歌实践教学平台习题)【合集】
本实验旨在学习类的继承关系、不同继承方式下的访问控制及利用虚基类解决二义性问题。主要内容包括: 1. **类的继承关系基础概念**:介绍继承的定义及声明派生类的语法。 2. **不同继承方式下对基类成员的访问控制**:详细说明`public`、`private`和`protected`继承方式对基类成员的访问权限影响。 3. **利用虚基类解决二义性问题**:解释多继承中可能出现的二义性及其解决方案——虚基类。 实验任务要求从`people`类派生出`student`、`teacher`、`graduate`和`TA`类,添加特定属性并测试这些类的功能。最终通过创建教师和助教实例,验证代码
58 5
|
2月前
|
存储 算法 搜索推荐
【C++面向对象——群体类和群体数据的组织】实现含排序功能的数组类(头歌实践教学平台习题)【合集】
1. **相关排序和查找算法的原理**:介绍直接插入排序、直接选择排序、冒泡排序和顺序查找的基本原理及其实现代码。 2. **C++ 类与成员函数的定义**:讲解如何定义`Array`类,包括类的声明和实现,以及成员函数的定义与调用。 3. **数组作为类的成员变量的处理**:探讨内存管理和正确访问数组元素的方法,确保在类中正确使用动态分配的数组。 4. **函数参数传递与返回值处理**:解释排序和查找函数的参数传递方式及返回值处理,确保函数功能正确实现。 通过掌握这些知识,可以顺利地将排序和查找算法封装到`Array`类中,并进行测试验证。编程要求是在右侧编辑器补充代码以实现三种排序算法
47 5
|
2月前
|
Serverless 编译器 C++
【C++面向对象——类的多态性与虚函数】计算图像面积(头歌实践教学平台习题)【合集】
本任务要求设计一个矩形类、圆形类和图形基类,计算并输出相应图形面积。相关知识点包括纯虚函数和抽象类的使用。 **目录:** - 任务描述 - 相关知识 - 纯虚函数 - 特点 - 使用场景 - 作用 - 注意事项 - 相关概念对比 - 抽象类的使用 - 定义与概念 - 使用场景 - 编程要求 - 测试说明 - 通关代码 - 测试结果 **任务概述:** 1. **图形基类(Shape)**:包含纯虚函数 `void PrintArea()`。 2. **矩形类(Rectangle)**:继承 Shape 类,重写 `Print
52 4
|
2月前
|
设计模式 IDE 编译器
【C++面向对象——类的多态性与虚函数】编写教学游戏:认识动物(头歌实践教学平台习题)【合集】
本项目旨在通过C++编程实现一个教学游戏,帮助小朋友认识动物。程序设计了一个动物园场景,包含Dog、Bird和Frog三种动物。每个动物都有move和shout行为,用于展示其特征。游戏随机挑选10个动物,前5个供学习,后5个用于测试。使用虚函数和多态实现不同动物的行为,确保代码灵活扩展。此外,通过typeid获取对象类型,并利用strstr辅助判断类型。相关头文件如&lt;string&gt;、&lt;cstdlib&gt;等确保程序正常运行。最终,根据小朋友的回答计算得分,提供互动学习体验。 - **任务描述**:编写教学游戏,随机挑选10个动物进行展示与测试。 - **类设计**:基类
41 3