【C++】类和对象练习——日期类的实现(二)

简介: 【C++】类和对象练习——日期类的实现(二)

5. 前置- -和后置- -的重载

那有了上面的练习,再实现前置- -和后置- -不是soeasy嘛。

前置- -:

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

先- -,后使用,返回- -之后的值。

59919103c3ed4046a848ba3df1d83e3f.png

后置- -:

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

先使用,后- -,返回- -之前的值。

b985c61e51c04df98328149dcee5f346.png

6. 日期-日期

上面我们搞了日期加减天数,那两个日期相减是不是也有意义啊,可以得出这两个日期之间差了多少天。

那如何计算两个日期之间相差的天数呢?

🆗,那这里给大家提供一种比较好实现的思路:
我们拿到两个日期之后,先把较小的那个日期找出来,然后用一个计数器,统计较小日期++的次数,当两个日期相等时停止,++的次数就是相差的天数。
另外如果是第一个日期大于第二个,结果应该是整数;如果第二个大于第一个,应该是负数。

我们来实现一下:

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

56ee63da7c6d4edcaf2aebc25e16c5e0.png

6cda8ef61167450d85f1783baef3d9f2.png

没有问题。

7. 流插入<<重载

那我们现在打印一个日期类对象的时候是不是都是去调用我们写的Print函数啊,那我们能不能想个办法打印日期类也能直接像这样打印:

36a8ef70262942948297616f8c0a6140.png

使用我们之前学的cout+<<去打印。

大家记不记得:

我们之前文章里学习C++输入输出的时候,其实只是浅浅的提了一下如何去用,并没有对cout、<<和>>进行过多讲解。
因为以我们那时的知识储备还不能很好的理解:

b9f54ddf8fc4460da7aa879ca4688281.png

那我们现在就可以再尝试多理解一点东西:


我们发现我们的自定义类型想用这些运算符是不是都要重载啊,除了赋值运算符以及取地址运算符,因为赋值重载和取地址重载是类的6个默认成员函数之中的,我们不写编译器会自动生成一个。但是在有些情况下根据实际情况我们还是需要自己写。

🆗,这是我们上一篇学习的知识,不用过多说明了。

然后呢我们还说C++里这样输入输出可以自动识别类型。

那为啥可以自动识别类型,其实是因为它这里对<<进行了函数重载。

5b5b25d13bb14bb18b33cad9984f6d26.png

为什么我们的内置类型可以直接用,因为库里面已经对这些类型都进行了重载,所以可以自动识别类型,是根据操作数的不同类型进行匹配。

那我们现在自定义类型想用怎么办,是不是需要自己重载啊。

那我们接下来就重载一下<<好吧:

void operator<<(ostream& out);

那想用<<是不是得使用cout,<<两个操作数,一个cout,一个是我们要打印得对象,cout是啥?

🆗,上面说了它是一个ostream 类型得对象,所以我们把cout作为参数传过去。

那这里out就用来接收cout,this指针指向得就是我们要打印得类对象。


来实现一下:

void Date::operator<<(ostream& out)
{
  out << _year << _month << _day << endl;
}

这样是不是就行了啊,它的成员变量都是内置类型,我们就可以使用<<直接打印了。

我们测试一下:

92c34838d429458f98823c774754cea3.png

但是我们使用的时候发现报错了。

这里操作数是不是写反了,为什么?

对于函数重载来说,两个参数的话,第一个参数是左操作数,第二个参数是右操作数。

但是对于类成员函数来说,第一个参数是不是隐藏的this指针啊,它指向我们调用该函数的对象,所以这里第一个参数是Date对象的地址。

那我们要调用的话,应该这样写:

89318616b9de4b3db8163c518cd68f33.png

但是这样写是不是好别扭啊。


怎么让它像内置类型那样使用啊。


那我们就要想办法让cout成为第一个参数,怎么做呢?

把函数重载写到类外面不就行了是吧。

没有说运算符重载不能写到类外面啊,我们写到类里面是为了啥,是不是只是为了可以访问private修饰的成员变量啊


那我们现在重载到外面:

3a4836ecb8df4ada84609c557d920348.png

那现在面临的问题是啥?

是在类外不能访问私有的成员变量,那怎么办?

可以把成员变量变成共有的public,但这样是不是就不能很好的保证封装性了;

或者可以提供Get方法,但C++一般不喜欢这样搞。

那还有什么方法呢?

🆗,就是用友元函数。

那怎么做呢?

我们把函数声明再放到类里面一份,但在前面加一个friend就行了:

0888f36f00a44c2d930ab76ec488dcb8.png

那这下我们就可以正常使用<<了

5d51b8e9b7c14bd88a8bd9f79d3e3335.png

但是呢:

0a4a108399c2409e8468e0d93cb455fa.png

这里不支持连续的流插入。为什么呢?

因为我们重载的没有返回值

4582fdc053ab4ba49984942e6a7edaf5.png

那应该返回啥?

是不是返回cout呀,让它能够继续打印后面的。

我们看其实库里面就是这么搞的:

f994cb1ad4014f74bcb9434ab03fc31d.png

ostream& operator<<(ostream& out, Date& d)
{
  out << d._year << "-" << d._month << "-" << d._day << endl;
  return out;
}

f8bb71e80a754ad7a138cffce8536d42.png

这样就行了。

8. 流提取>>重载

那紧接着,我们再来重载一下流提取:

istream& operator>>(istream& in, Date& d)
{
  in >> d._year >> d._month >> d._day;
  return in;
}

测试一下:

61eddc7aac8849bea57d4fe11443c3a5.png

就完成了。

9. 总结

那最后呢,还要给大家说明一点:

我们在之前的类和对象第一篇其实就提到了:

2651e612d6b54e7b8c117aca0f707511.png

就是类的成员函数如果直接定义在类里面,编译器是会将其当成内联函数的,不管你有没有加inline关键字。


那我们在学习内联函数的时候也说了:


一般建议将函数规模较小(即函数不是很长,具体没有准确的说法,取决于编译器内部实现)、不是递归、且频繁调用的函数实现成内联函数。

所以说,类里面的成员函数如果规模较小,适合做内联函数的,直接定义在类里面。

不过我们今天写的这个日期类,里面我是所有成员函数的声明和定义都分离了,大家以后可以根据实际情况,有些成员函数直接定义在类里面。

但是我们说了内联函数不是只是对编译器的一个建议嘛,如果规模较大的函数就算我们实现成内联函数编译器也不一定按照内联函数处理。

那在类里面也是这样,就算我们把全部的类成员函数都直接定义在类里面,也不一定会全部当做内联函数处理,编译器也还是会看它具体适不适合做内联。


另外还有一点:


上一篇文章我们不是还学习了const成员函数嘛,大家还可以看一看我们日期类的这么多成员函数,哪一个在函数内部不需要改变调用它的对象,是不是把它实现成const成员函数也是比较好的。

10. 源码展示

最后,把完整的源码给大家展示一下:

  1. Date.h
#pragma once
#include <iostream>
#include <stdbool.h>
#include <assert.h>
using namespace std;
class Date
{
  //友元
  friend ostream& operator<<(ostream& out, const Date& d);
  friend istream& operator>>(istream& in, Date& d);
public:
  int GetMonthDay(int year, int month);
  //构造函数
  Date(int year = 1, int month = 1, int day = 1);
  //拷贝构造函数
  //Date(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);
  void Print();
  bool operator==(const Date& d);
  Date& operator+=(int day);
  Date operator+(int day);
  //前置++
  Date& operator++();
  //后置++
  Date operator++(int);
  Date& operator-=(int day);
  Date operator-(int day);
  Date& operator--();
  Date operator--(int);
  //日期-日期
  int operator-(Date d);
  //赋值重载(对于Date类用默认生成的就行)
  //d1=d2(this就是d1,d就是d2)
  /*Date& operator=(const Date& d)
  {
    if (this != &d)
    {
      _year = d._year;
      _month = d._month;
      _day = d._day;
    }
    return *this;
  }*/
private:
  int _year;
  int _month;
  int _day;
};
//<<
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);
  1. Date.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "Date.h"
int Date::GetMonthDay(int year, int month)
{
  assert(month > 0 && month < 13);
  int MonthArr[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 MonthArr[month];
  }
}
//构造函数
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;
    _year = 1;
    _month = 1;
    _day = 1;
  }
}
//拷贝构造函数
//Date::Date(const Date& d)
//{
//  _year = d._year;
//  _month = d._month;
//  _day = d._day;
//}
bool Date::operator<(const Date& d)
{
  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)
{
  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);
}
void Date::Print()
{
  cout << _year << "-" << _month << "-" << _day << endl;
}
bool Date::operator==(const Date& d)
{
  return _year == d._year
    && _month == d._month
    && _day == d._day;
}
//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;
//}
Date& Date::operator+=(int day)
{
  if (day < 0)
  {
    *this -= -day;
    return *this;
  }
  _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)
{
  Date tmp(*this);
  tmp += day;
  return tmp;
}
//前置++
Date& Date::operator++()
{
  *this += 1;
  return *this;
}
//后置++
Date Date::operator++(int)
{
  Date tmp(*this);
  *this += 1;
  return tmp;
}
Date& Date::operator-=(int day)
{
  if (day < 0)
  {
    *this += -day;
    return *this;
  }
  _day -= day;
  while (_day <= 0)
  {
    --_month;
    if (_month == 0)
    {
      --_year;
      _month = 12;
    }
    _day += GetMonthDay(_year, _month);
  }
  return *this;
}
Date Date::operator-(int day)
{
  Date tmp(*this);
  tmp -= day;
  return tmp;
}
Date& Date::operator--()
{
  *this -= 1;
  return *this;
}
Date Date::operator--(int)
{
  Date tmp(*this);
  *this -= 1;
  return tmp;
}
//日期-日期
int Date::operator-(Date d)
{
  Date max = *this;
  Date min = d;
  int flag = 1;
  if (*this < d)
  {
    max = d;
    min = *this;
    flag = -1;
  }
  int n = 0;
  while (min != max)
  {
    ++min;
    ++n;
  }
  return n * flag;
}
//<<
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;
  return in;
}
  1. Test.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "Date.h"
void Datetest1()
{
  Date d1(2023, 2, 15);
  d1.Print();
  Date d2 = d1 + (-100);
  d2.Print();
  /*Date d3 = ++d1;
  d3.Print();*/
}
void Datetest2()
{
  Date d1(2023, 2, 16);
  d1.Print();
  Date d2 = d1--;
  d1.Print();
  d2.Print();
}
void Datetest3()
{
  Date d1;
  cin >> d1;
  cout << d1 << endl;
}
int main()
{
  //Datetest3();
  return 0;
}

🆗,那这篇文章就到这里,欢迎大家指正!!!

下一篇文章,我们会对类和对象再做一些补充和收尾!!!

a402fd5c199245899e624ce131c33869.png

目录
相关文章
|
10小时前
|
C++ Linux
|
10小时前
|
编译器 C++
【C++】继续学习 string类 吧
首先不得不说的是由于历史原因,string的接口多达130多个,简直冗杂… 所以学习过程中,我们只需要选取常用的,好用的来进行使用即可(有种垃圾堆里翻美食的感觉)
7 1
|
10小时前
|
算法 安全 程序员
【C++】STL学习之旅——初识STL,认识string类
现在我正式开始学习STL,这让我期待好久了,一想到不用手撕链表,手搓堆栈,心里非常爽
15 0
|
10小时前
|
存储 安全 测试技术
【C++】string学习 — 手搓string类项目
C++ 的 string 类是 C++ 标准库中提供的一个用于处理字符串的类。它在 C++ 的历史中扮演了重要的角色,为字符串处理提供了更加方便、高效的方法。
16 0
【C++】string学习 — 手搓string类项目
|
10小时前
|
设计模式 安全 算法
【C++入门到精通】特殊类的设计 | 单例模式 [ C++入门 ]
【C++入门到精通】特殊类的设计 | 单例模式 [ C++入门 ]
17 0
|
10小时前
|
C语言 C++
【C++】string类(常用接口)
【C++】string类(常用接口)
21 1
|
10小时前
|
Java C++ Python
【C++从练气到飞升】06---重识类和对象(二)
【C++从练气到飞升】06---重识类和对象(二)
|
10小时前
|
编译器 C++
【C++从练气到飞升】06---重识类和对象(一)
【C++从练气到飞升】06---重识类和对象(一)
|
10小时前
|
存储 编译器 C语言
【C++从练气到飞升】02---初识类与对象
【C++从练气到飞升】02---初识类与对象