C++:类之六脉神剑——默认成员函数

简介: C++:类之六脉神剑——默认成员函数


一、默认成员函数

如果一个类中什么成员都没有,简称为 空类

空类中真的什么都没有吗?并不是,任何类在什么都不写时,编译器会自动生成以下 6个默认成员

函数

  • 默认成员函数:用户没有显式实现,编译器会生成的成员函数称为默认成员函数。

  • 构造函数(Constructor):当创建一个新的对象实例时,会调用构造函数。它用于初始化对象的状态。
  • 析构函数(Destructor):当对象被销毁时调用,用于执行清理工作,如关闭文件、释放内存等。
  • 拷贝构造函数(Copy Constructor):用于创建一个新对象,其内容与另一个现有对象相同。
  • 赋值重载:把一个对象赋值给另一个对象;
  • 取地址重载普通对象取地址操作;
  • 取地址重载(const):const对象取地址操作;

本章我们将学习六个个默认成员函数


二、构造函数

2.1  概念

typedef int dataOfStackType;
typedef struct stack
{
  dataOfStackType* a;
  int top;
  int capacity;
}stack;
void StackInit(stack* ps);
//...
 int main()
 {
   stack s;
   StackInit(&s);
   //...
   return 0;
 }
  • 对于Date类,可以通过 Init 公有方法给对象设置日期,但如果每次创建对象时都调用该方法设置信息,未免有点麻烦,那能否在对象创建时,就将信息设置进去呢?

构造函数是一个特殊的成员函数,名字与类名相同,创建类类型对象时由编译器自动调用,以保证每个数据成员都有 一个合适的初始值,并且在对象整个生命周期内只调用一次


2.2  特性

构造函数是一个特殊的成员函数。构造函数虽然叫作构造,但是其主要作用并不是开辟空间创建对象,而是初始化对象

构造函数之所以特殊,是因为相比于其它成员函数,它具有如下特性

  • 函数名与类名相同;
  • 无返回值;
  • 对象实例化时,编译器自动调用对应的构造函数;
  • 构造函数可以重载;
class Date
{
public:
  //无参的构造函数
  Date()
  {};
  //带参的构造函数
  Date(int year,int month,int day)
  {
    _year = year;
    _month = month;
    _day = day;
  }
private:
  int _year;
  int _month;
  int _day;
};
void TestDate()
{
  Date d1;//调用无参构造函数(自动调用)
  Date d2(2023, 3, 29);//调用带参构造函数(自动调用)
}

注意:

     如果通过无参构造函数创建对象时,对象后面不用跟括号,否则就成了函数声明   。

错误示范:

Date d3();
    // 以上代码的函数:声明了d3函数,该函数无参,返回一个日期类型的对象
     // warning C4930: “Date d3(void)”: 未调用原型函数
  • 如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成。
class Date
{
public:
  //若用户没有显示定义,则编译器自动生成。
  /*Date(int year,int month,int day)
  {
    _year = year;
    _month = month;
    _day = day;
  }*/
private:
  int _year;
  int _month;
  int _day;
};
 int main()
 {
 Date d1;
 return 0;
 }

解析:

  1. 将Date类中构造函数屏蔽后,代码可以通过编译,因为编译器生成了一个无参的默认构造函 数
  2. 将Date类中构造函数放开,代码编译失败,因为一旦显式定义任何构造函数,编译器将不再 生成
  3. 无参构造函数,放开后报错:error C2512: “Date”: 没有合适的默认构造函数可用
  • 默认生成构造函数,对内置类型成员不作处理;对自定义类型成员,会调用它的默认构造函数

     C++把类型分成内置类型(基本类型)和自定义类型。内置类型就是语言提供的数据类型,  如:int、char、double…,自定义类型就是我们使用class、struct、union等自己定义的类型。

class Time
{
public:
  Time()
  {
    cout << "Time()" << endl;
    _hour = 0;
    _minute = 0;
    _second = 0;
  }
private:
  int _hour;
  int _minute;
  int _second;
};
class Date
{
public:
  void print()
  {
    cout << _year << "-" << _month << "-" << _day << endl;
  }
private:
  // 基本类型(内置类型)
  int _year;
  int _month;
  int _day;
  // 自定义类型
  Time _t;
  
};
int main()
{
  Date d;
  d.print();
  return 0;
}

由上可以看出:默认构造函数未对内置类型做处理;但是默认构造函数对自定义成员_t做了处理,调用了它的默认构造函数Time()

注意:

        C++11 中针对内置类型成员不初始化的缺陷,又打了补丁,即: 内置类型成员变量在

类中声明时可以给默认值

举例如下:

class Date
{
public:
//...
  void print()
  {
    cout << _year << "-" << _month << "-" << _day << endl;
  }
private:
  //使用默认值
  int _year = 0;
  int _month = 0;
  int _day = 0;
};
void TestDate2()
{
  Date d2;
  d2.print();
}
  •  无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。
#include<iostream>
using namespace std;
class Date
{
public:
  //无参的默认构造函数
  Date()
  {
  }
  //全缺省的默认构造函数
  Date(int year = 0, int month = 0, int day = 0)
  {
    _year = year;
    _month = month;
    _day = day;
  }
  void print()
  {
    cout << _year << "-" << _month << "-" << _day << endl;
  }
private:
  int _year = 0;
  int _month = 0;
  int _day = 0;
};
// 以下测试函数能通过编译吗?
void Test()
{
  Date d1;
}

结果:

默认构造函数:

  1. 无参的构造函数
  2. 全缺省的构造函数
  3. C++编译器生成的无参的构造函数

即三种必须要有一种,如果没有默认的构造函数(写的构造函数不是无参的,也不是全缺省的)就会报错。

我们这里推荐写全缺省构造函数(方便+万全)


三、析构函数

3.1 概念

析构函数构造函数功能相反,析构函数不是完成对对象本身的销毁,局部对象销毁工作是由编译器完成的。而对象在销毁时会自动调用析构函数,完成对象中资源的清理工作

栈桢的销毁和开辟不归我们管,我们只管堆上的空间的开辟和销毁,而析构函数主要运用于自动调用销毁堆上的空间

析构函数不像构造函数一样每个类都需要,更多的是像栈这样在堆上动态开辟空间的类需要,

有了析构函数,我们再也不用担心创建对象(或定义变量)后由于忘记释放内存而造成内存泄漏了。

3.2 特性

  • 析构函数名是在类名前加上字符 ~
  • 无参数;
  • 无返回值;
  • 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数;
  • 析构函数不能重载;
  • 对象生命周期结束时,C++编译系统系统自动调用析构函数。

举例:

class Date
{
public:
  Date()
  {
    cout << "Date()" << endl;
  }
  ~Date()
  {
    cout << "~Date()" << endl;
  }
private:
  int _year = 0;
  int _month = 0;
  int _day = 0;
};
void TestDate3()
{
  Date d3;
  //d3生命周期结束时自动调用构造函数
}

结果:

  • 编译器生成的默认析构函数,对自定类型成员调用它的析构函数,对内置类型不做处理;
#include<iostream>
using namespace std;
 
class Time
{
public:
  ~Time()
  {
    cout << "~Time()" << endl;
  }
private:
  int _hour;
  int _minute;
  int _second;
};
class Date
{
private:
  // 基本类型(内置类型)
  int _year = 1970;
  int _month = 1;
  int _day = 1;
  // 自定义类型
  Time _t;
};
int main()
{
  Date d; 
  return 0;
}

解析:

内置类型成员,销毁时不需要资源清理,最后系统直接将其内存回收即可;而_t是Time类对 象,所以在d销毁时,要将其内部包含的Time类的_t对象销毁,所以要调用Time类的析构函数。但是main函数中不能直接调用Time类的析构函数,实际要释放的是Date类对象,所以编译器会调用Date类的析构函数,而Date没有显式提供,则编译器会给Date类生成一个默认的析构函数,目的是在其内部 调用Time 类的析构函数,即当Date对象销毁时,要保证其内部每个自定义对象都可以正确销毁 。

  • 如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,比如Date类;有资源申请时,一定要写,否则会造成资源泄漏,比如stack类。
  • 析构函数调用的顺序:局部变量(先定义后析构)--->局部静态--->全局(静态)对象(先定义后析构)

四、拷贝构造函数

4.1 概念

拷贝构造函数:只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时由编译器自动调用。

  • 拷贝构造函数的功能就如同它的名字——拷贝。我们可以用一个已存在的对象来创建一个与已存在对象一模一样的新的对象
int main()
{
  Date d1(2023, 7, 21);
  Date d2(d1);
//  Date d2 = d1;//等价上面的写法
 
    return 0;
}

4.2 特性

拷贝构造函数也是特殊的成员函数,其特征如下:

1. 拷贝构造函数是构造函数的一个重载形式。

2. 拷贝构造函数的参数只有一个且必须是类类型对象的引用,使用传值方式编译器直接报错,因为会引发无穷递归调用。

class Date
{
public:
 Date(int year = 1900, int month = 1, int day = 1)
 {
 _year = year;
 _month = month;
 _day = day;
 }
 // Date(const Date& d)   // 正确写法
    Date(const Date d)   // 错误写法:编译报错,会引发无穷递归
 {
 _year = d._year;
 _month = d._month;
 _day = d._day;
 }
private:
 int _year;
 int _month;
 int _day;
};
int main()
{
 Date d1;
 Date d2(d1);
 return 0;
}
  • 当拷贝构造函数的参数采用传值的方式时,创建对象d2,会调用它的拷贝构造函数d1会作为实参传递给形参d。不巧的是,实参传递给形参本身又是一个拷贝,会再次调用形参的拷贝构造函数…如此便会引发无穷的递归。

3. 若未显式定义,编译器会生成默认的拷贝构造函数。 默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝

class Date
{
public:
  //构造函数
  Date(int year = 0, int month = 0, int day = 0)
  {
    //cout << "Date()" << endl;
    _year = year;
    _month = month;
    _day = day;
  }
  //未显式定义拷贝构造函数
  /*Date(const Date& d)
  {
    _year = d._year;
    _month = d._month;
    _day = d._day;
  }*/
  void print()
  {
    cout << _year << "-" << _month << "-" << _day << endl;
  }
private:
  int _year = 0;
  int _month = 0;
  int _day = 0;
};
void TestDate()
{
  Date d1(2023, 3, 31);
  //调用拷贝构造创建对象
  Date d2(d1);
  d2.print();
}

注意:在编译器生成的默认拷贝构造函数中,内置类型是按照字节方式直接拷贝的,而自定义类型是调用其拷贝构造函数完成拷贝的。

4. 类中如果没有涉及资源申请时,拷贝构造函数写不写都可以;一旦涉及到资源申请时,则拷贝构造函数是一定要写的,否则就是浅拷贝

#include<iostream>
#include<assert.h>
using namespace std;
 
typedef int DataType;
class stack {
public:
  stack(size_t capacity = 4) {
    _a = (int*)malloc(sizeof(int) * capacity);
    assert(_a);
    _capacity = capacity;
    _size = 0;
  }
  void push(DataType x) {
    //...
    _a[_size] = x;
    _size++;
  }
  bool Empty() {
    return _size == 0;
  }
  DataType top() {
    return _a[_size - 1];
  }
  void pop() {
    _size--;
  }
  ~stack(){
    cout << "~stack()" << endl;
    if (_a)
    {
      free(_a);
      _a = nullptr;
    }
    _size = _capacity = 0;
  }
private:
  int* _a;
  int _capacity;
  int _size;
};
int main() {
  stack st1;
  st1.push(1);
  st1.push(2);
  st1.push(3);
  stack st2(st1);
  return 0;
}

注意:

这段程序的运行结果是程序崩溃了, 两对象的生命周期结束时自动调用析构函数,也就意味着s2先调用默认析构,调用~stack()释放st2指针所指空间,指针置为nullptr;但是,st2所指空间释放不影响st1指针的所指空间仍为已经释放的空间,导致st1变成野指针,此时再次调用析构函数但是同一块空间不能释放2次,所以有些时候默认拷贝函数(值拷贝)会导致程序出错。

  • 编译器自动生成的拷贝构造函数是浅拷贝

问题:那我们如何解决上诉问题呢?

  • 自己实现拷贝构造函数,实现深拷贝
#include<iostream>
#include<assert.h>
using namespace std;
 
typedef int DataType;
class stack {
public:
  stack(size_t capacity = 4) {
    DataType* _a = (DataType*)malloc(sizeof(DataType) * capacity);
    assert(_a);
    _capacity = capacity;
    _size = 0;
  }
  stack(const stack& st) {
    DataType* tmp = (DataType*)malloc(sizeof(DataType) * st._capacity);
    assert(tmp);
    memcpy(tmp, _a, sizeof(DataType) * st._size);
    _a = tmp;
    _size = st._size;
    _capacity = st._capacity;
  }
  void push(DataType x) {
    //...
    _a[_size] = x;
    _size++;
  }
  bool Empty() {
    return _size == 0;
  }
  DataType top() {
    return _a[_size - 1];
  }
  void pop() {
    _size--;
  }
  ~stack(){
    cout << "~stack()" << endl;
    if (_a)
    {
      free(_a);
      _a = nullptr;
    }
    _size = _capacity = 0;
  }
private:
  int* _a;
  int _capacity;
  int _size;
};
int main() {
  stack st1;
  stack st2(st1);
  return 0;
}

5. 拷贝构造函数典型调用场景

  • 使用已存在对象创建新对象;
  • 函数参数类型为类类型对象;
  • 函数返回值类型为类类型对象。
class Date
{
public:
  Date(int year, int minute, int day)
  {
    cout << "Date(int,int,int):" << this << endl;
  }
  Date(const Date& d)
  {
    cout << "Date(const Date& d):" << this << endl;
  }
  ~Date()
  {
    cout << "~Date():" << this << endl;
  }
private:
  int _year;
  int _month;
  int _day;
};
Date Test(Date d)
{
  Date temp(d);
  return temp;
}
int main()
{
  Date d1(2022, 1, 13);
  Test(d1);
  return 0;
}

为了提高程序效率,一般对象传参时,尽量使用引用类型,返回时根据实际场景,能用引用尽量使用引用


五、赋值运算符重载

5.1 运算符重载

5.1.1 概念

C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。

运算符重载的目的:让自定义类型像内置类型一样使用运算符

运算符重载结构: 返回值类型     operator操作符(参数列表)

例如

//类成员函数
bool operator==(Date &d2);
5.1.2 特性

运算符重载有如下特性:

  • 重载操作符必须有一个类类型参数
  • 不能通过连接其他符号来创建新的操作符:比如operator@、operator?等;
  • 用于内置类型的运算符,其含义不能改变,例如:int类型的+,不能改变其含义;
  • 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this;
  • .*  ::  sizeof  ?:  .注意以上5个运算符不能重载。这个经常在笔试选择题中出现。

有了上述的特性描述,我们还可以实现== 、<、 >、 <=、 >=、 +、 -、 ++、 --、等一系列操作符的重载。

下面实现运算符==、<

#include<iostream>
using namespace std;
 
class Date {
public:
  Date(int year = 2024, int month = 2, int day = 8) {
    _year = year;
    _month = month;
    _day = day;
  }
  bool operator==(const Date& y) {
    return _year == y._year
      && _month == y._month
      && _day == y._day;
  }
  bool operator<(const Date& y) {
    if (_year < y._year) {
      return true;
    }
    else if (_year == y._year) {
      if (_month < y._month)
        return true;
      else if (_month == y._month)
        return _day < y._day;
    }
    return false;
  }
private:
  int _year;
  int _month;
  int _day;
};
int main() {
  Date d1(2024,2,1);
  Date d2(2024, 2, 3);
  cout << (d1 == d2) << endl;
  cout << (d1 < d2) << endl;
  return 0;
}

5.2  赋值运算符重载

5.2.1 概念

与之前讲的构造函数析构函数等默认成员函数相同,赋值运算符重载也属于6个默认成员函数之一。作为与众不同的默认成员函数。

5.2.2 特性

其有以下特性

1、赋值运算符重载格式:

参数类型const T&,传递引用可以提高传参效率;

返回值类型T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值检测是否自己给自己赋值;
返回*this
:要复合连续赋值的含义;

#include<iostream>
using namespace std;
class Date {
public:
  Date(int year = 2024, int month = 2, int day = 8) {
    _year = year;
    _month = month;
    _day = day;
  }
  Date(const Date& d)
  {
    _year = d._year;
    _month = d._month;
    _day = d._day;
  }
 
  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;
};
int main() {
  Date d1(2024, 2, 1);
  Date d2;
  d2 = d1;//赋值操作
  return 0;
}

2、赋值运算符只能重载成类的成员函数不能重载成全局函数

namespace Aron
{
    class Date
  {
    //...
  };
}
// 赋值运算符重载成全局函数,注意重载成全局函数时没有this指针了,需要给两个参数
Date& operator=(Date& left, const Date& right)
{
  if (&left != &right)
  {
    left._year = right._year;
    left._month = right._month;
    left._day = right._day;
  }
  return left;
}

上面程序会出现编译错误 :error C2801: “operator =”必须是非静态成员

出错原因是:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。

简而言之,全局写一个,类里面没写,编译器自动生成一个,那到底调用哪一个?---产生歧义

3.、用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。

注意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值。如果类中未涉及到资源管理,赋值运算符是否实现都可以;一旦涉及到资源管理则必须要实现。

这里赋值重载与拷贝构造函数的特性非常相似。

但是注意区分拷贝构造函数赋值运算符重载函数的使用场景:

Date d1(2024, 1, 1);
Date d2(d1);
Date d3 = d1;

Date d1(2024, 1, 1)调用的是构造函数; Date d2(d1)调用的是拷贝构造函数Date d3 = d1不是赋值运算符重载函数,第三句代码也是拷贝构造函数。

拷贝构造函数:用一个已经存在的对象去构造初始化另一个即将创建的对象。

赋值运算符重载函数:在两个对象都已经存在的情况下,将一个对象赋值给另一个对象。


六、取地址操作符重载

6个默认成员函数只剩两个——取地址重载与const取地址重载。但是,这两个函数实在没有实现的必要,因为我们自己实现与编译器自动实现出来的效果是一样的。

class Date
{
public:
  Date* operator&()
  {
    return this;
  }
  const Date* operator&()const
  {
    return this;
  }
private:
  int _year; // 年
  int _month; // 月
  int _day; // 日
};

七、const成员

const修饰的成员函数称之为const成员函数const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改

请思考下面的几个问题:

1. const对象可以调用非const成员函数吗?不可以,权限的放大

2. 非const对象可以调用const成员函数吗?可以,权限的缩小

3. const成员函数内可以调用其它的非const成员函数吗?不可以,权限的放大

4. 非const成员函数内可以调用其它的const成员函数吗?可以,权限的缩小

总结:

成员函数,如果是一个只对成员变量进行读访问的函数,建议在后面加const,const和非const对象都可以调用。

成员函数,如果是一个只对成员变量进行读+写访问的函数,不能在后面加const,否则不能修改this

注意:权限放大不允许,权限缩小允许;指针和引用赋值才存在权限放大


八、日期类的实现

我们总结上文中的运算符重载,整理一下完整的日期类的实现。此处我们使用多文件的形式实现日期计算器

  • Date.h文件中进行头文件包含命名空间展开类的声明内联函数定义等;
  • Date.cpp文件中进行对类成员函数的定义。

8.1 Date.h

#include<iostream>
#include<assert.h>
using namespace std;
class Date {
public:
  //构造函数
  Date(int year = 1, int month = 1, int day = 1);
  //拷贝构造
  Date(const Date& d);
  
  //获取天数
  int GetDate(int year, int month) 
  {
    assert(month > 0 && month < 13);
    const static int a[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 a[month];
  }
  //日期比较
  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+=(int day);//本身要改变--->&返回
  // 日期+天数
  Date operator+(int day)  const;//本身不需要改变--->值返回
  // 日期-=天数
  Date& operator-=(int day) ;
  
  // 日期-天数
    Date operator-(int day)  const;
  
  // 前置++
  Date& operator++();
  // 后置++
  Date operator++(int);
  // 后置--
  Date operator--(int);
  
  // 前置--
  Date& operator--();
  //赋值运算符重载
  Date& operator=(const Date& d);
  
  // 日期-日期 返回天数
  int operator-(const Date& d) const;
  
  //日期合法检查
  bool CheckInvalid() ;
  //友元函数声明
  friend ostream& operator<<(ostream& out, const Date& d);//流插入操作符重载
  friend istream& operator>>(istream& in, Date& d);//流提取操作符重载
private:
  int _year;
  int _month;
  int _day;
};

8.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;
  if (!CheckInvalid())
  {
    cout<<"日期不合法"<<endl;
  }
}
Date::Date(const Date& d)
{
    _year = d._year;
    _month = d._month;
    _day = d._day;
  
}
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)
  {
    return true;
  }
  else if (_year == d._year)
  {
    if (_month < d._month)
    {
      return true;
    }
    else if (_month == d._month)
    {
      return  _day < d._day;
    }
  }
  return false;
}
bool Date:: operator>(const Date& d)    const
{
  return !(*this == d || *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 || *this == d);
}
// 日期+=天数
Date& Date::operator+=(int day)//本身要改变--->&返回
{
  if (day < 0)
  {
    return *this -= (-day);
  }
  _day += day;
  while (_day > GetDate(_year, _month))
  {
    _day -= GetDate(_year, _month);
    ++_month;
    if (_month == 13)
    {
      ++_year;
      _month = 1;
    }
    
  } 
  return *this;
}
// 日期+天数
Date Date::operator+(int day)  const//本身不需要改变--->值返回
{
  Date tmp(*this);
  tmp += day;
  return tmp;
}
// 日期-=天数
Date & Date::operator-=(int day)
{
  if (day < 0)
  {
    return *this+=(-day);
  }
  _day -= day;
  while (_day <=0)
  {
    
    --_month;
    if (_month == 0)
    {
      --_year;
      _month = 12;
    }
    _day += GetDate(_year, _month);
  }
  return *this;
}
// 日期-天数
Date Date:: operator-(int day) const
{
  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--()
{
  *this -= 1;
  return *this;
}
// 后置--
Date Date::operator--(int)
{
  Date tmp(*this);
  *this -= 1;
  return tmp;
}
//赋值运算符重载
Date& Date::operator=(const Date& d) 
{
  if(*this != d)
  {
    _year = d._year;
    _month = d._month;
    _day = d._day;
  }
  return *this;
}
// 日期-日期 返回天数
int Date::operator-(const Date& d) const
{
  Date max = *this;//拷贝构造
  Date min = d;
  int flag = 1;
  if (max < min)
  {
    Date tmp = max;//拷贝构造
    max = min;//赋值
    min = tmp;//赋值
    flag = -1;
  }
  int n = 0;
  while (min != max)
  {
    ++min;
    ++n;
  }
  return n*flag;
}
//日期合法检查
bool Date::CheckInvalid() 
{
  if (_year < 0 || _month < 1 || _month>13 || _day<1 || _day>GetDate(_year, _month))
  {
    return false;
  }
  else
  {
    return true;
  }
}
//友元函数声明
ostream& operator<<(ostream& out, const Date& d)//流插入操作符重载
{
  out << d._year << d._month << d._day << endl;
  return out;
}
istream& operator>>(istream& in, Date& d)//流提取操作符重载
{
  while (1)
  {
    in >> d._year >> d._month >> d._day;
    if (d.CheckInvalid())
    {
      break;
    }
    else
    {
      cout << "输入非法日期,请重新输入" << endl;
    }
  }
  return in;
}

希望大家阅读完可以有所收获,同时也感谢各位铁汁们的支持。文章有任何问题可以在评论区留言,百题一定会认真阅读!

相关文章
|
22小时前
|
存储 编译器 C语言
从C语言到C++_11(string类的常用函数)力扣58和415(中)
从C语言到C++_11(string类的常用函数)力扣58和415
5 0
|
22小时前
|
存储 C语言 C++
从C语言到C++_11(string类的常用函数)力扣58和415(上)
从C语言到C++_11(string类的常用函数)力扣58和415
5 0
|
22小时前
|
编译器 C语言 C++
从C语言到C++⑤(第二章_类和对象_中篇)(6个默认成员函数+运算符重载+const成员)(下)
从C语言到C++⑤(第二章_类和对象_中篇)(6个默认成员函数+运算符重载+const成员)
4 1
|
22小时前
|
存储 编译器 程序员
从C语言到C++④(第二章_类和对象_上篇)->类->封装->this指针(下)
从C语言到C++④(第二章_类和对象_上篇)->类->封装->this指针
4 0
|
1天前
|
C++
【C++基础】类class
【C++基础】类class
9 1
|
1天前
|
安全 程序员 编译器
C++程序中的基类与派生类转换
C++程序中的基类与派生类转换
8 1
|
1天前
|
C++
C++程序中的类成员函数
C++程序中的类成员函数
8 1
|
1天前
|
C++
C++程序中的类封装性与信息隐蔽
C++程序中的类封装性与信息隐蔽
8 1
|
1天前
|
C++
C++程序中的类声明与对象定义
C++程序中的类声明与对象定义
11 1
|
1天前
|
数据安全/隐私保护 C++
C++程序中的派生类
C++程序中的派生类
7 1