【C++语言】Date类的代码实现(操作符重载运用)

简介: 【C++语言】Date类的代码实现(操作符重载运用)

前言

在上一章节中,我们学习了类和对象的一些内容,包括:类的相关特征、类的默认成员函数、以及操作符重载(重点)。本节就综合前面的相关内容,实现一个Date类。


Date类的构思

我们设想的Date类包括以下操作:


  1. 可以计算n天前\后的日期(+、-、+=、-=等);
  2. 判断两个日期的关系(大于,小于等);
  3. 可以计算两个日期之间相差多少天;


Date类的相关实现

基本框架(默认成员函数)

因为Date类型比较简单,属性只有内置类型,所以大部分默认成员函数就可以满足需求。

class Date
{
public:
  //构造函数:全缺省的默认构造函数,但需要判断合法性,所以需要自己定义
  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);
    }
  }
  //拷贝构造函数:Date类属性全是内置类型,可以不写拷贝构造
  
  //赋值运算符重载:Date类属性全是内置类型,赋值运算符重载也可以不用写
  
  //析构函数:Date类属性全是内置类型,赋值运算符重载也不用写
private:
  int _year;
  int _month;
  int _day;
};


计算n天前\后的日期

计算n天后基本思路:

日期加上天数,天数相加,判断是否超出当月的日期天数(循环判断),若超出,则月数进1,同时判断月数是否等于13,若等于则再向年进1,月变回1月;


设计流程:

  1. GetMonthDay()获得当月的天数;
  2. Date Date::operator # (int day) const (#代表多种运算符重载);

1.GetMonthDay()

功能:传入年和月,得出该月的天数。

参数:(int year, int month)

返回:int (天数)


注意:方法一般设置在头文件之外,头文件(Date.h)声明函数方法,(Date.cpp)实现方法,因此方法前需要加入Date::类域

int Date::GetMonthDay(int year, int month)
{
  //静态设置每月天数,二月需要判断是否为闰年得出
  //之所以静态,是减少频繁创造过程的损失
  static int daysArr[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) 
  //不太好,应当容易简单判断的条件放在&&前,优化
  if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
  {
    return 29;
  }
  else
  {
    return daysArr[month];
  }
}
  1. Date Date::operator+=(int day) (+=运算符重载);
    功能:实现Date类和int整形相加,并且直接修改该对象;
    参数: (int day)
    返回: Date&
Date& Date::operator+=(int day)
{
  if (day < 0) //考虑我们输入的day是负数
  {
    return *this -= -day;
  }

  _day += day;
  while (_day > GetMonthDay(_year, _month))
  {
    _day -= GetMonthDay(_year, _month);
    ++_month;
    if (_month == 13)
    {
      ++_year;
      _month = 1;
    }
  }

  return *this;
}
  1. Date Date::operator+(int day) const (+运算符重载);
    功能:实现Date类和int整形相加,返回最终日期。
    参数: (int day)
    返回: Date (最终日期)
Date Date::operator+(int day)  const
{
  //直接复用+=号
  Date tmp(*this);
  tmp += day;
  return tmp;
}

计算n天前基本思路:

日期减去天数,天数相减,判断天数是否为负数或者零(循环判断),若为负数,则月数减1,同时判断月数是否等于0,若等于则再向年借1,月变回12月;

  1. Date& Date::operator-=(int day) (-=运算符重载)
    功能:实现Date类和int整形相减,且直接修改该对象。
    参数: (int day)
    返回: Date&
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;
}
  1. Date Date::operator-(int day) const (-运算符重载)
    功能:实现Date类和int整形相减,返回最终日期。
    参数: (int day)
    返回: Date
Date Date::operator-(int day) const
{
  Date tmp = *this;
  tmp -= day;
  return tmp;
}


补充:前置++、后置++说明

前置++,返回++后的值,实现时返回原本对象即可,所以可以引用返回。

后置++,返回++前的值,需要创建临时变量储存,临时变量出函数自动销毁,所以只能传值返回;

但我们运算符重载的时候发现,他们都以Date& operator++()为声明,这会导致编译器无法区分,从而报错。从而为了区别,C++这样规定:

前置++声明:Date& operator++();

后置++声明:Date operator++(int);

为区分他们,在后置++的传参部分加入(int)int占位,以示区分,并没有其他作用。

代码实现很简单,但必须认识到这点(减减一并实现):

// 前置++
Date& Date::operator++()
{
  *this += 1;
  return *this;
}
// 后置++
// 增加这个int参数不是为了接收具体的值,仅仅是占位,跟前置++构成重载
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;
}

判断两个日期的关系(大于,小于等);

我们需要先判断两个日期的大小关系,才可以实现两个日期的相减;

大小关系操作数我们通常只需要实现两个最基本的,其他复用就可以了:大于或者小于,以及等于。

bool operator<(const Date& x) const

功能:判断两个日期的大小,该对象是否小于x对象;

参数:(const Date& x)

返回值: bool 布尔类型

bool Date::operator<(const Date& x) const
{
  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) const
{
  return _year == x._year
    && _month == x._month
    && _day == x._day;
}

// 复用
// d1 <= d2
bool Date::operator<=(const Date& x) const
{
  return *this < x || *this == x;
}

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

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

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

可以计算两个日期之间相差多少天

基本思路:用最简单的思路,一天一天计算。判断并找出谁大谁小,用小的日期不断++,++过程中用临时变量计数,直到小的日期等于大的日期结束。

int Date::operator-(const Date& d) const

功能:计算两个日期之间相差多少天

参数:(const Date& d)

返回值: int (相差天数)

int Date::operator-(const Date& d) const
{
//假设法:任意假设大小;
  Date max = *this;
  Date min = d;
  int flag = 1;//巧妙运用1和-1

  if (*this < d)
  {
    max = d;
    min = *this;
    flag = -1;
  }

  int n = 0;
  while (min != max)
  {
    ++min;
    ++n;
  }

  return n * flag;
}


补充:流输入以及流提取操作符实现:

这里我们只是简单认识其中的一些问题即可,内容实现需要i/o相关库的基础,不容易懂。

  1. <<(>>) 流输入(流提取)他们无法在类域中实现,因为我们在使用cout和cin的过程中,第一参数并不是我们的Date(或其他类对象)而是cout和cin,所以我们需要定义为类外的函数方法;
  2. 我们要实现连续输入或输出,所以返回参数应当是ostream&或istream&;
  3. 外部定义实现的函数无法访问类中private的属性,因此需要类有相关方法或者设置该外部定义为友元函数;
class Date
{
  // 友元函数声明
  friend ostream& operator<<(ostream& out, const Date& d);
  friend istream& operator>>(istream& in, Date& d);
  ...其他代码
}

代码实现:

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;
}

完整代码如下:

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() const
  {
    cout << _year << "-" << _month << "-" << _day << endl;
  }


  bool operator<(const Date& x) const;
  bool operator==(const Date& x) const;
  bool operator<=(const Date& x) const;
  bool operator>(const Date& x) const;
  bool operator>=(const Date& x) const;
  bool operator!=(const Date& x) const;

  int GetMonthDay(int year, int month);

  // d1 + 100
  Date& operator+=(int day);
  Date operator+(int day) const;

  Date& operator-=(int day);
  Date operator-(int day) const;

  Date& operator++();
  Date operator++(int);

  Date& operator--();
  Date operator--(int);

  int operator-(const Date& d) const;

  
private:
  int _year;
  int _month;
  int _day;
};

ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);




Date.cpp

#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) const
{
  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) const
{
  return _year == x._year
    && _month == x._month
    && _day == x._day;
}

// 复用
// d1 <= d2
bool Date::operator<=(const Date& x) const
{
  return *this < x || *this == x;
}

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

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

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

int Date::GetMonthDay(int year, int month)
{
  static int daysArr[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)
  if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
  {
    return 29;
  }
  else
  {
    return daysArr[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;
}

// d1 + 100
Date Date::operator+(int day)  const
{
  Date tmp(*this);
  tmp += day;
  return tmp;

  /*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)
{
  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) const
{
  Date tmp = *this;
  tmp -= day;
  return tmp;
}

// 前置++
Date& Date::operator++()
{
  *this += 1;
  return *this;
}

// 后置++
// 增加这个int参数不是为了接收具体的值,仅仅是占位,跟前置++构成重载
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;

  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)
{
  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类做案例。

相关文章
|
1月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
44 0
|
1月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
112 0
|
1月前
|
C++
爱心代码 C++
这段C++代码使用EasyX图形库生成动态爱心图案。程序通过数学公式绘制爱心形状,并以帧动画形式呈现渐变效果。运行时需安装EasyX库,教程链接:http://【EasyX图形库的安装和使用】https://www.bilibili.com/video/BV1Xv4y1p7z1。代码中定义了屏幕尺寸、颜色数组等参数,利用随机数与数学函数生成动态点位,模拟爱心扩散与收缩动画,最终实现流畅的视觉效果。
66 0
|
3月前
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
114 12
|
4月前
|
存储 算法 安全
企业员工数据泄露防范策略:基于 C++ 语言的布隆过滤器算法剖析[如何防止员工泄密]
企业运营过程中,防范员工泄密是信息安全领域的核心议题。员工泄密可能致使企业核心数据、商业机密等关键资产的流失,进而给企业造成严重损失。为应对这一挑战,借助恰当的数据结构与算法成为强化信息防护的有效路径。本文专注于 C++ 语言中的布隆过滤器算法,深入探究其在防范员工泄密场景中的应用。
77 8
|
4月前
|
编译器 C++
类和对象(下)C++
本内容主要讲解C++中的初始化列表、类型转换、静态成员、友元、内部类、匿名对象及对象拷贝时的编译器优化。初始化列表用于成员变量定义初始化,尤其对引用、const及无默认构造函数的类类型变量至关重要。类型转换中,`explicit`可禁用隐式转换。静态成员属类而非对象,受访问限定符约束。内部类是独立类,可增强封装性。匿名对象生命周期短,常用于临时场景。编译器会优化对象拷贝以提高效率。最后,鼓励大家通过重复练习提升技能!
|
4月前
|
编译器 C++
类和对象(中 )C++
本文详细讲解了C++中的默认成员函数,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载和取地址运算符重载等内容。重点分析了各函数的特点、使用场景及相互关系,如构造函数的主要任务是初始化对象,而非创建空间;析构函数用于清理资源;拷贝构造与赋值运算符的区别在于前者用于创建新对象,后者用于已存在的对象赋值。同时,文章还探讨了运算符重载的规则及其应用场景,并通过实例加深理解。最后强调,若类中存在资源管理,需显式定义拷贝构造和赋值运算符以避免浅拷贝问题。
|
4月前
|
存储 编译器 C++
类和对象(上)(C++)
本篇内容主要讲解了C++中类的相关知识,包括类的定义、实例化及this指针的作用。详细说明了类的定义格式、成员函数默认为inline、访问限定符(public、protected、private)的使用规则,以及class与struct的区别。同时分析了类实例化的概念,对象大小的计算规则和内存对齐原则。最后介绍了this指针的工作机制,解释了成员函数如何通过隐含的this指针区分不同对象的数据。这些知识点帮助我们更好地理解C++中类的封装性和对象的实现原理。
|
4月前
|
设计模式 安全 C++
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
98 16
|
4月前
|
安全 C++
【c++】继承(继承的定义格式、赋值兼容转换、多继承、派生类默认成员函数规则、继承与友元、继承与静态成员)
本文深入探讨了C++中的继承机制,作为面向对象编程(OOP)的核心特性之一。继承通过允许派生类扩展基类的属性和方法,极大促进了代码复用,增强了代码的可维护性和可扩展性。文章详细介绍了继承的基本概念、定义格式、继承方式(public、protected、private)、赋值兼容转换、作用域问题、默认成员函数规则、继承与友元、静态成员、多继承及菱形继承问题,并对比了继承与组合的优缺点。最后总结指出,虽然继承提高了代码灵活性和复用率,但也带来了耦合度高的问题,建议在“has-a”和“is-a”关系同时存在时优先使用组合。
236 6