从C语言到C++⑥(第二章_类和对象_中篇_续)大练习(日期类)+笔试选择题(上)

简介: 从C语言到C++⑥(第二章_类和对象_中篇_续)大练习(日期类)+笔试选择题

1. 日期类详细实现

上一篇我们讲了6个默认成员函数和运算符重载等知识,复习链接:

从C语言到C++⑤(第二章_类和对象_中篇)(6个默认成员函数+运算符重载+const成员)_GR C的博客-CSDN博客

为了能够更好地讲解运算符重载和融合以前知识,我们将来实现 一个"日期类" ,

日期类的拷贝构造、赋值、析构我们都可以不用写,让编译器自己生成就行了。

构造是要写的,剩下的你想写什么就写什么。

1.1 构造函数和打印函数

和以前做大练习一样,规范一点,我们声明与定义分离开来。

先放个样例,然后后面就不放了,最后面会放完整代码。

Date.h:

#include <iostream>
using namespace std;
 
class Date
{
public:
  // 构造会频繁调用,所以直接放在类里面(类里面的成员函数默认为内联)
  Date(int year = 1, int month = 1, int day = 1)
  {
    _year = year;
    _month = month;
    _day = day;
  }
  void Print() const;  // 打印函数
 
private:
  int _year;
  int _month;
  int _day;
};

Date.cpp:

#include "Date.h"
 
// void Date::Print(const Date* const this)
void Date::Print() const
{
  cout << _year << "年" << _month << "月" << _day << "日" << endl;
}

Test.cpp:

#include "date.h"
 
void TestDate1()
{
  Date d1;
  d1.Print();
 
  Date d2(2023, 5, 4);
  d2.Print();
}
 
int main()
{
  TestDate1();
 
  return 0;
}

(记录一下五一放了五天,然后五四再放半天然后还在写博客,泪目泪目)

这里的 Print 是可以加 const 的,而构造函数这里修改了成员变量,是不能加 const 的。

上一篇我们说过,加 const 是很好的,只要不改变都建议加上 const 。

我们以前讲知识点没想过:如果我们给构造函数的日期是一个非法的日期呢?

如果有人输入了这种日期,还是能给他打印出来,这不合理,


所以我们需要设计一个函数去判断,用户输入的日期到底合不合法。


因为每个月天数不统一,所以在写判断日期合法的算法前,


我们需要先设计一个后面也用到的可以获取一年中每个月对应天数的 GetMonthDay 函数。


如何设计呢?写12个 if else?可以是可以,就是有点搓。


用 switch case 可能还好一点。和计数排序差不多,我们这里可以写个简单的哈希来解决,


我们把每个月的天数放到一个数组里,为了方便还可以把下标为 0 的位置空出来,


这里还要考虑到我们上面提到的闰年问题,闰年二月会多一天。


如果月份为 2,我们就进行判断,如果是闰年就让获取到的 day + 1 即可。

// 会频繁调用,所以直接放在类里面定义作为inline
int GetMonthDay(int year, int month)// 获取某年某月的天数
{
  //这里的数组会频繁使用,所以加上static
  static int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int day = days[month];
  if (month == 2
    && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))//先判断是否是2月
  {
    day += 1;
  }
  return day;
}

如果传入的月份是2月,就判断是否是闰年。

这里还有一个小细节就是我们是先判断传入的月份2月的,

根据 && 的特性,碰到假,后面就不会判断了,这就是一些写代码的好习惯。

然后就可以写一个检查日期是否合法的函数了:

// 会频繁调用,所以还是直接放在类里面定义作为inline
bool CheckDate()
{
  if (_year >= 1
    && _month > 0 && _month < 13
    && _day > 0 && _day <= GetMonthDay(_year, _month))
  {
    return true;
  }
  else
  {
    return false;
  }
}

这里一个条件放一行也是个好习惯。然后我们的构造函数就可以这样:

// 构造会频繁调用,所以直接放在类里面(类里面的成员函数默认为内联)
Date(int year = 1, int month = 1, int day = 1)
{
  _year = year;
  _month = month;
  _day = day;
 
  //if (!CheckDate())
  //{
  //  Print();
  //  cout << "刚构造的日期非法" << endl;
  //}
 
  assert(CheckDate());
}

这里使用暴力的方法,记得#include,然后这里就会直接报错:

然后值得一提的是类里面的成员函数和成员变量等都是被编译器看成一个整体的,

所以不用管哪个放在哪个的上面。

1.2 六个比较运算符重载

上一篇我们在讲运算符重载的时候讲了判断日期类等于的例子,

根据逻辑:任何一个类,只需要写一个> == 或者 < ==重载 剩下的比较运算符重载复用即可

日期的判断很简单,我们只需要挨个对比就可以了,结果返回布尔值,没什么好说的。

我们这里写判断等于和判断大于然后直接放出日期类比较运算符重载的部分,

判断等于:

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)
    || (_year == d._year && _month > d._month)
    || (_year == d._year && _month == d._month && _day > d._day))
  {
    return true;
  }
  else
  {
    return false;
  }
}

Date.h:

#pragma once
 
#include <iostream>
#include <assert.h>
using namespace std;
 
class Date
{
public:
  // 构造会频繁调用,所以直接放在类里面(类里面的成员函数默认为内联)
  Date(int year = 1, int month = 1, int day = 1)//构造
  {
    _year = year;
    _month = month;
    _day = day;
    //if (!CheckDate())
    //{
    //  Print();
    //  cout << "刚构造的日期非法" << endl;
    //}
    assert(CheckDate());
  }
 
  void Print() const;  // 打印
 
  int GetMonthDay(int year, int month)// 获取某年某月的天数
  {
    static int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int day = days[month];
    if (month == 2
      && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
    {
      day += 1;
    }
    return day;
  }
 
  bool CheckDate()// 检查日期是否合法
  {
    if (_year >= 1
      && _month > 0 && _month < 13
      && _day > 0 && _day <= GetMonthDay(_year, _month))
    {
      return true;
    }
    else
    {
      return false;
    }
  }
 
  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;
 
private:
  int _year;
  int _month;
  int _day;
};

Date.c:

#include "Date.h"
 
// void Date::Print(const Date* const this)
void Date::Print() const
{
  cout << _year << "年" << _month << "月" << _day << "日" << endl;
}
 
// 任何一个类,只需要写一个> == 或者 < ==重载 剩下比较运算符重载复用即可
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)
    || (_year == d._year && _month > d._month)
    || (_year == d._year && _month == d._month && _day > d._day))
  {
    return true;
  }
  else
  {
    return false;
  }
}
 
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);
}
 
bool Date::operator<=(const Date& d) const
{
  return !(*this > d);
}

Test.c:

#include "Date.h"
 
void TestDate1()
{
  Date d1;
  d1.Print();
 
  Date d2(2023, 5, 4);
  d2.Print();
 
  Date d3(2026, 5, 1);
  Date d4(2020, 5, 20);
 
  cout << (d2 > d3) << endl;
  cout << (d2 == d3) << endl;
  cout << (d2 != d3) << endl;
  cout << (d2 >= d4) << endl;
  cout << (d2 < d4) << endl;
  cout << (d2 <= d4) << endl;
}
 
int main()
{
  TestDate1();
 
  return 0;
}

1.3 日期+=天数 和 日期+天数

日期加一个日期没什么意义,但是加天数的场景就很多了。

比如我们想让当前日期加100天:

Date d1(2023, 5, 4);
d1 += 100;
d1.Print();
 
Date d2(2023, 5, 4);
d3 = d2 + 100;
d2.Print();
d3.Print();

体会了上面代码复用的方便,思考一下先实现+=还是+呢?


+= 原来的值变了,+ 原来的值没有变,返回的都是+之后的值


+ 还要调用两次拷贝,所以先实现+= 好一点点


日期加天数把进位搞定就可以了,我们把天数全都加到day上,


只需要判断加完日期后天数合不合法,


看它加完后的天数有没有超出这个月的天数,如果超过了就不合法。


这个我们刚才已经实现过 GetMonthDay 了,这里就直接拿来用就行了。


如果不合法,我们就进位。天满了往月进,月再满就往年进。


因为出了作用域对象还在,我们可以使用引用返回减少拷贝:

Date& Date::operator+=(int day)//这里没考虑day是负数的情况,最后放的代码加上了
{
  _day += day;
  while (_day > GetMonthDay(_year, _month))
  {
    _day -= GetMonthDay(_year, _month);
    _month++;
    if (_month == 13)
    {
      _year++;
      _month = 1;
    }
  }
  return *this;
}

+= 是改变 "本体",但是 + 并不会,所以这里可以加个 const 修饰一下。

+ 和 += 很类似,也是通过 "判断" 就可以实现的,复用一下 += :

Date Date::operator+(int day) const//不改变,用const
{
  Date ret = *this; 
  ret += day;
 
  return ret;// 出了作用域ret对象就不在了,所以不能用引用返回
}

因为我们 + 是复用 += 的,所以我们只测试+应该就没什么问题

上面的日期可以用网上搜的日期计算器搜索来验证:


从C语言到C++⑥(第二章_类和对象_中篇_续)大练习(日期类)+笔试选择题(中):https://developer.aliyun.com/article/1513650

目录
相关文章
|
3天前
|
C++
C++一分钟之-类与对象初步
【6月更文挑战第20天】C++的类是对象的蓝图,封装数据和操作。对象是类的实例。关注访问权限、构造析构函数的使用,以及内存管理(深拷贝VS浅拷贝)。示例展示了如何创建和使用`Point`类对象。通过实践和理解原理,掌握面向对象编程基础。
30 2
C++一分钟之-类与对象初步
|
4天前
|
存储 编译器 C++
|
4天前
|
C++
C++类和类模板——入门
C++类和类模板——入门
10 1
|
2天前
|
C语言
C语言--生日日期输出--年月日,一行输出--之间没有间隔,若月份为个位,在前面添加0
C语言--生日日期输出--年月日,一行输出--之间没有间隔,若月份为个位,在前面添加0
|
2天前
|
C语言
C语言----开学----输出一个数字,表示开学日期是星期几
C语言----开学----输出一个数字,表示开学日期是星期几
|
3天前
|
C++
C++ 实现一个不能被copy的类
C++ 实现一个不能被copy的类
|
10天前
|
编译器 数据安全/隐私保护 C++
c++primer plus 6 读书笔记 第十三章 类继承
c++primer plus 6 读书笔记 第十三章 类继承
|
6天前
|
数据安全/隐私保护 C++
C++ 中的类是一种用户定义的数据类型,用于表示具有相似特征和行为的对象的模板。
C++ 中的类是一种用户定义的数据类型,用于表示具有相似特征和行为的对象的模板。
|
9天前
|
存储 编译器 C++
【C++初阶】—— 类和对象 (中)
【C++初阶】—— 类和对象 (中)
20 3
|
9天前
|
编译器 C++
【C++初阶】—— 类和对象 (下)
【C++初阶】—— 类和对象 (下)
11 2