C++第九弹---类与对象(六)

简介: C++第九弹---类与对象(六)



1、日期类的分析和设计

1.1、日期类的功能说明

创建一个日期类,通过运算符重载实现对日期的相关计算以及比较功能。包含如下:

1、重载日期的大小比较(>  ==  >=  <  <=  !=)

2、重载赋值操作符

3、重载日期+= / -=天数

4、重载日期+ / -天数

5、重载日期前置++ / --

6、重载日期后置++ / --

7、重载日期 - 日期

1.2、日期类的分析和设计

1.2.1、数据结构的分析

创建一个日期类,成员变量包括年月日(最好将成员变量权限设置为private,这样在类外就无法访问类中成员变量,起到一定的保护作用),内部实现获取某年某月的天数的函数,为了实现分文件设计,类中只需声明构造函数,拷贝构造函数以及日期类需要实现的重载函数

1.2.2、文件结构设计

之前我们在C语言中学习了多文件的形式对函数的声明和定义,这里我们C++实践⼀下,我们设计三个文件:

test.cpp    //文件中日期类的测试逻辑
Date.cpp  //文件中写类中重载函数的实现等
Date.h      //文件中写日期类需要的数据类型和函数声明等

建议:写一些代码就测试一些代码。

2、日期类的结构分析

2.1、创建日期类及声明

注意:在实现操作函数之前判断是否会修改成员变量的值,如果不需要改变成员变量的值,可以使用const修饰来保护代码。

class Date
{
public:
  // 构造函数
  Date(int year, int month, int day);
  // 拷贝构造函数
  // d2(d1)
  Date(const Date& d);
  // 赋值运算符重载
  // d2 = d3 -> d2.operator=(&d2, d3)
  // >运算符重载
  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) const;
  // 日期-=天数
  Date& operator-=(int day);
  // 前置++
  Date& operator++();
  // 后置++
  Date operator++(int);
  // 后置--
  Date operator--(int);
  // 前置--
  Date& operator--();
  // 日期-日期 返回天数
  int operator-(const Date& d) const;
private:
  int _year;
  int _month;
  int _day;
};

2.2、在类内实现获取天数函数

根据我们日期的规则,只有2月的天数是不同的,此时我们可以创建一个数组来存放对应年份月份的天数,如果是平年的2月则为28天,如果是闰年的2月则为29天,因此我们在创建完数组之后判断一下即可。

uu们可能不太了解什么情况是闰年,闰年的规则如下:

1、每4年为一个闰年,每100年为平年。即年份%4==0且年份%100!=0.

2、每400年为一个闰年。即年份%400==0。

代码实现如下:

// 获取某年某月的天数
int GetMonthDay(int year, int month)
{
  int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };//下标表示月份
  if (((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))&&(month == 2) )
    return 29;
  return days[month];
}

uu们可能一开始就写出上面的代码, 那么这个代码有没有问题呢?或者说效率高不高呢?

小林的答案是有问题,效率也没有尽可能进行优化,原因如下:

1、可以将该函数加上const进行修饰,因为后面重载函数的实现中可能会被const修饰,那么如果没有const修饰,可以调用该函数,如果有const修饰的函数就不能调用此函数。但是该函数加上const修饰,不管是否有const进行修饰函数,都可以调用。

2、没有对月份进行判断,我们的月份只有1到12月,但是我们不做判断传入负数或者大于12的月份,因此此处可以用我们C语言所学习的断言语句。

3、创建的数组是在栈区创建的,但是获取天数的函数会经常调用,那么调用一次函数就会创建一个栈空间,效率很低,此处我们可以使用static修饰,将数组放在静态区,那么就只会创建一次。

4、判断是否为闰年时,我们可以做小小的调整,根据C语言学习的短路求值原则,与运算中左边的为假则结束运算,因此我们可以将容易判断的条件放在左边。

经过调整的获取某年某月的天数函数如下:

// 获取某年某月的天数
  int GetMonthDay(int year, int month) const
  {
    assert(month > 0 && month < 13);//月份的判断
    // 因为该函数会经常调用,但是数组的值一直是不需要变化的,因此可以使用静态数组
    // 好处是在静态区只会创建一份变量
    static int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
    if ((month == 2) && ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0) ))
      return 29;
    return days[month];
  }

注意:该函数实现的年数对负数是不支持的,1582年也可能会出现问题,因为1582年少了10天。

2.3、在类外实现构造函数

注意:在类外实现类中声明的构造函数需要使用域作用符。

// 构造函数
Date::Date(int year, int month, int day)
{
  _year = year;
  _month = month;
  _day = day;
}

2.4、在类外实现拷贝构造函数

// 拷贝构造函数
// d2(d1)
Date::Date(const Date& d)
{
  _year = d._year;
  _month = d._month;
  _day = d._day;
}

2.5、在类外实现赋值运算符重载

// 赋值运算符重载
// d2 = d3 -> d2.operator=(&d2, d3)
Date& Date::operator=(const Date& d)
{
  _year = d._year;
  _month = d._month;
  _day = d._day;
  return *this;
}

2.6、在类外实现日期的比较

// >运算符重载
bool Date::operator>(const Date& d) const
{
  if (_year > d._year)
    return true;
  else if (_year == d._year)
  {
    if (_month > d._month)
      return true;
    else if (_month == d._month)
    {
      if (_day > d._day)
        return true;
    }
  }
  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);
}
// !=运算符重载
bool Date::operator != (const Date& d) const
{
  return !(*this == d);
}

注意:此处使用的思想是先实现两个比较操作,然后通过位运算操作符实现其他的操作。

2.7、在类外实现日期+-天数

// 日期+=天数
Date& Date::operator+=(int 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 temp(*this);
//  temp += day;
//  return temp;
//}
 
// 日期+天数 ---直接实现
Date Date::operator+(int day) const
{
  Date temp(*this);
  temp._day += day;
  while (temp._day > GetMonthDay(_year, _month))
  {
    temp._day -= GetMonthDay(temp._year, temp._month);
    ++temp._month;
    if (temp._month == 13)
    {
      ++temp._year;
      temp._month = 1;
    }
  }
  return temp;
}
// 日期-=天数
Date& Date::operator-=(int 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 temp(*this);
  Date temp(*this);
  temp -= day;
  return temp;
}
 日期-天数 ---直接实现
//Date Date::operator-(int day) const
//{
//  //Date temp(*this);
//  Date temp(*this);
//  temp._day -= day;
//  while (temp._day <= 0)
//  {
//    --temp._month;
//    if (temp._month == 0)
//    {
//      --temp._year;
//      temp._month = 12;
//    }
//    temp._day += GetMonthDay(temp._year, temp._month);
//  }
//  return temp;
//}
// 前置++
Date& Date::operator++()
{
  *this += 1;
  return *this;
}
// 后置++
Date Date::operator++(int)
{
  Date temp(*this);
  *this += 1;
  return temp;
}
// 后置--
Date Date::operator--(int)
{
  Date temp(*this);
  *this -= 1;
  return temp;
}
// 前置--
Date& Date::operator--() const
{
  *this -= 1;
  return *this;
}

2.8、在类外实现日期-日期

思想:计算第一个类与第二个类的差值,我们在前面已经实现了++和比较操作,此处只需要先判断哪个日期类大,小的日期类++多少次等于大的日期类就是相差的天数。

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

3、日期类分文件的代码实现

3.1、test.cpp

#define _CRT_SECURE_NO_WARNINGS
#include "Date.h"
int main()
{
  Date d1(2022, 1, 1);
  d1 += 1;
  Date d2(2022, 1, 2);
  d2 = d2 + 10;
  Date d3(2022, 1, 3);
  d3 -= 2;
  
  Date d4(2022, 1, 4);
  d4 = d4 - 10;
  Date d5(2022, 1, 5);
  Date d6 = d5--;
  //Date d6 = d5.operator--(10);  //后置--
  Date d7(2022, 1, 18);
  Date d8(2022, 1, 8);
  cout << (d7 - d8) << endl;
  return 0;
}

3.2、Date.cpp

#define _CRT_SECURE_NO_WARNINGS
#include "Date.h"
// 构造函数
Date::Date(int year, int month, int day)
{
  _year = year;
  _month = month;
  _day = day;
}
// 拷贝构造函数
// d2(d1)
Date::Date(const Date& d)
{
  _year = d._year;
  _month = d._month;
  _day = d._day;
}
// 赋值运算符重载
// d2 = d3 -> d2.operator=(&d2, d3)
Date& Date::operator=(const Date& d)
{
  _year = d._year;
  _month = d._month;
  _day = d._day;
  return *this;
}
// >运算符重载
bool Date::operator>(const Date& d) const
{
  if (_year > d._year)
    return true;
  else if (_year == d._year)
  {
    if (_month > d._month)
      return true;
    else if (_month == d._month)
    {
      if (_day > d._day)
        return true;
    }
  }
  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);
}
// !=运算符重载
bool Date::operator != (const Date& d) const
{
  return !(*this == d);
}
// 日期+=天数
Date& Date::operator+=(int 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 temp(*this);
//  temp += day;
//  return temp;
//}
 
// 日期+天数 ---直接实现
Date Date::operator+(int day) const
{
  Date temp(*this);
  temp._day += day;
  while (temp._day > GetMonthDay(_year, _month))
  {
    temp._day -= GetMonthDay(temp._year, temp._month);
    ++temp._month;
    if (temp._month == 13)
    {
      ++temp._year;
      temp._month = 1;
    }
  }
  return temp;
}
// 日期-=天数
Date& Date::operator-=(int 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 temp(*this);
  Date temp(*this);
  temp -= day;
  return temp;
}
 日期-天数 ---直接实现
//Date Date::operator-(int day) const
//{
//  //Date temp(*this);
//  Date temp(*this);
//  temp._day -= day;
//  while (temp._day <= 0)
//  {
//    --temp._month;
//    if (temp._month == 0)
//    {
//      --temp._year;
//      temp._month = 12;
//    }
//    temp._day += GetMonthDay(temp._year, temp._month);
//  }
//  return temp;
//}
// 前置++
Date& Date::operator++()
{
  *this += 1;
  return *this;
}
// 后置++
Date Date::operator++(int)
{
  Date temp(*this);
  *this += 1;
  return temp;
}
// 后置--
Date Date::operator--(int)
{
  Date temp(*this);
  *this -= 1;
  return temp;
}
// 前置--
Date& Date::operator--()
{
  *this -= 1;
  return *this;
}
// 日期-日期 返回天数
int Date::operator-(const Date& d) const
{
  int flag = 1;
  Date max = *this;
  Date min = d;
  if (*this < d)
  {
    flag = -1;
    max = d;
    min = *this;
  }
  int n = 0;
  while (min != max)
  {
    min++;
    n++;
  }
  return n * flag;
}

3.3、Date.h

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
class Date
{
public:
  // 获取某年某月的天数
  int GetMonthDay(int year, int month) const
  {
    assert(month > 0 && month < 13);
    // 因为该函数会经常调用,但是数组的值一直是不需要变化的,因此可以使用静态数组
    // 好处是在静态区只会创建一份变量
    static int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
    if ((month == 2) && ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)))
      return 29;
    return days[month];
  }
  // 构造函数
  Date(int year, int month, int day);
  // 拷贝构造函数
  // d2(d1)
  Date(const Date& d);
  // 赋值运算符重载
  // d2 = d3 -> d2.operator=(&d2, d3)
    // >运算符重载
  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) const;
  // 日期-=天数
  Date& operator-=(int day);
  // 前置++
  Date& operator++();
  // 后置++
  Date operator++(int);
  // 后置--
  Date operator--(int);
  // 前置--
  Date& operator--();
  // 日期-日期 返回天数
  int operator-(const Date& d) const;
private:
  int _year;
  int _month;
  int _day;
};

总结

本篇博客就结束啦,谢谢大家的观看,如果公主少年们有好的建议可以留言喔,谢谢大家啦!

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