C++进阶指南 - 类&对象(中)

目录

🎨 类的6个默认成员函数

🎨 构造函数

🎨 析构函数

🎨 拷贝构造函数

🎨 赋值运算符重载

🎨 const成员

🎨 具体实现一个Date类(代码实现

 

类的6个默认成员函数

如果一个类中什么成员都没有,简称为空类。空类中什么都没有吗?并不是的,任何一个类在我们不写的情
况下,都会自动生成下面6个默认成员函数。

class Date {};

在这里插入图片描述

构造函数主要完成初始化工作,析构函数主要完成清理工作


构造函数

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

构造函数是特殊的成员函数,需要注意的是,构造函数的虽然名称叫构造,但是需要注意的是构造函数的主
要任务并不是开空间创建对象,而是初始化对象。

其特征如下:

  1. 函数名与类名相同。
  2. 无返回值。
  3. 对象实例化时编译器自动调用对应的构造函数。
  4. 构造函数可以重载。

如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定
义编译器将不再生成。


C++里面把类型分成两种:内置类型(基本类型),自定义类型

内置类型: int/char/double/指针/内置类型数组 等等

自定义类型: struct/class 定义的类型

我们不写编译器默认生成构造函数,对于内置类型不做初始化处理

对于自定义类型回去调用它的无参默认构造函数初始化

如果没有默认构造函数就会报错

任何一个类的默认构造函数就是— 不用参数就可以调用,有三个:全缺省、无参、我们不写编辑器默认生成的

无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。注意:无参
构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数
,都可以认为是默认成员函数。


析构函数

概念

前面通过构造函数的学习,我们知道一个对象时怎么来的,那一个对象又是怎么没呢的?
析构函数:与构造函数功能相反,析构函数不是完成对象的销毁,局部对象销毁工作是由编译器完成的。

而对象在销毁时会自动调用析构函数,完成对象的一些资源清理工作。

特性

析构函数是特殊的成员函数。
其特征如下:

  1. 析构函数名是在类名前加上字符 ~。
  2. 无参数无返回值。
  3. 一个类有且只有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。
  4. 对象生命周期结束时,C++编译系统系统自动调用析构函数。
class SeqList
{ 
public :
 SeqList (int capacity = 10)
 {
		 _pData = (DataType*)malloc(capacity * sizeof(DataType));
		 assert(_pData);
		 
		 _size = 0;
		 _capacity = capacity;
		 
 }
 
 ~SeqList()
 {
		 if (_pData)
		 {
		 free(_pData ); // 释放堆上的空间
		 _pData = NULL; // 将指针置为空
		 _capacity = 0;
		 _size = 0;
		 }
 }
 
private :
 int* _pData ;
 size_t _size;
 size_t _capacity;
};

关于编译器自动生成的析构函数,是否会完成一些事情呢?下面的程序我们会看到,编译器生成的默认
析构函数,对会自定类型成员调用它的析构函数。


拷贝构造函数

概念

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

特征

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

  1. 拷贝构造函数是构造函数的一个重载形式
  2. 拷贝构造函数的参数只有一个且必须使用引用传参,使用传值方式会引发无穷递归调用。
Date(const Date& d)
    {
        _year = d._year;
        _mouth = d._mouth;
        _day = d._day;
    }

在这里插入图片描述

调用拷贝构造,需要先传参数,传值传参又是一个拷贝构造 → 调用拷贝构造,需要先传参数,传值传参又是一个拷贝构造…(无穷递归)


若未显示定义,系统生成默认的拷贝构造函数

默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝我们叫做浅拷贝,或者值拷贝。

默认生成拷贝函数:

  1. 内置类型成员,会完成按字节序进行的拷贝(浅拷贝)
  2. 自定义类型的成员变量,会去调用它的拷贝构造运算符重载
  3. 拷贝构造我们不写生成的默认拷贝函数对于内置类型和自定义类型都会进行拷贝处理。但是处理细节不一样,这个跟构造和析构是不一样的

赋值运算符重载

运算符重载

C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。
函数名字为:关键字operator后面接需要重载的运算符符号
函数原型:返回值类型 operator操作符(参数列表)

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


class Date
{
public:
    Date(int year = 2022, int mouth = 5, int day = 5)
    {
        _year = year;
        _mouth = mouth;
        _day = day;
    }
private:
    int _year;
    int _mouth;
    int _day;
}
int main()
{
    Date d1(2022, 1, 16);
    Date d2(2022, 1, 31);
    Date d3(2022, 2, 16);
    
    d1 > d2;
    int day = d2 - d1;
    
    return 0;
}

针对上面这个样例,我们存在日期之间的差值,日期之间的前后的操作,需要通过运算符重载来实现

// 判断两个日期的大小
bool operator>(const Date& d1, const Date& d2)
{
    if(d1._year > d2._year) return true;
    else if(d1._year == d2._year && d1._month > d2._month) return true;
    else if(d1._year == d2._year && d1._month == d2._month && d1._day > d2._day) return true;
    else return false;
}
// 在类里面定义
class Date
{
public:
    Date(int year = 2022, int month = 5, int day = 5)
    {
        _year = year;
        _month = month;
        _day = day;
    }
    // bool operator>(Date* const this, const Date& d)
    bool 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;
        else return false;
    }
private:
    int _year;
    int _month;
    int _day;
}

赋值运算符重载

Date& operator=(const Date& d)
{
    if(this != &d)
    {
        _year = d._year;
        _month = d._month;
        _day = d._day;
    }
    return *this;
}

赋值运算符主要有四点:

  1. 参数类型
  2. 返回值
  3. 检测是否自己给自己赋值
  4. 返回***this**
  5. 一个类如果没有显式定义赋值运算符重载,编译器也会生成一个,完成对象按字节序的值拷贝

编译器默认生成赋值重载,跟拷贝重载做的事情完全类似

  1. 内置类型成员,会按字节序拷贝 — 浅拷贝
    2.自动类型成员,会调用它的operator=

总结

默认生成的这四个默认成员函数

构造和析构处理机制基本类似的

拷贝构造和赋值重载处理机制基本类似的


const成员

const修饰类的成员函数

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

在这里插入图片描述

class Date
{ 
public :
 void Display ()
 {
	 cout<<"Display ()" <<endl;
	 cout<<"year:" <<_year<< endl;
	 cout<<"month:" <<_month<< endl;
	 cout<<"day:" <<_day<< endl<<endl ;
 }
 void Display () const
 {
	 cout<<"Display () const" <<endl;
	 cout<<"year:" <<_year<< endl;
	 cout<<"month:" <<_month<< endl;
	 cout<<"day:" <<_day<< endl<<endl;
 }
private :
	 int _year ; // 年
	 int _month ; // 月
	 int _day ; // 日
};
void Test ()
{
	 Date d1 ;
	 d1.Display ();
	 
	 const Date d2;
	 d2.Display ();
}

取地址及const取地址操作符重载

这两个默认成员函数一般不用重新定义 ,编译器默认会生成

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

具体实现一个Date类(代码实现)

Date.cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include "Date.h"

Date::Date(int year, int mouth, int day)
{
	_year = year;
	_month = mouth;
	_day = day;

	if(!(_year >= 0 
		&&(_month > 0 && _month < 13)
		&& (_day > 0 && _day <= GetMonthDay(_year, _month))))
	{
		cout << "非法日期->";
		this->Print();
	}
}

void Date::Print()
{
	cout << _year << '-' << _month << '-' << _day << endl;
}

int Date::GetMonthDay(int year, int month)
{
	static int monthDayArray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	int day = monthDayArray[month];
	// 将是否为2月放在最前面
	if (month == 2 && (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
	{
		day += 1;
	}
	return day;
}

Date& Date::operator+=(int day)
{
	_day += day;
	while (_day > GetMonthDay(_year, _month))
	{
		_day -= GetMonthDay(_year, _month);
		++_month;

		if (_month == 13)
		{
			_month = 1;
			_year++;
		}
	}

	return *this;
}

Date Date::operator+(int day)
{
	Date ret(*this);
	ret.operator+=(day);
	// ret += day
	return ret;
}

Date& Date::operator-=(int day)
{
	if (day < 0)
	{
		return *this += -day;
	}
	_day -= day;
	while (_day <= 0)
	{
		--_month;
		if (_month == 0)
		{
			--_year;
			_month = 12;
		}

		_day += GetMonthDay(_year, _month);
	}

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

Date Date::operator++()
{
	*this += 1;
}

Date Date::operator++(int)
{
	*this += 1;
}

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

bool Date::operator==(const Date& d)
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

// 实现功能上的复用
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 || *this == d;
}

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

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

int Date::operator-(const Date& d)
{
	Date max = *this;
	Date min = d;
	int flag = 1;
	if (*this < d)
	{
		max - d;
		min = *this;
		flag = -1;
	}

	int count = 0;
	while (min != max)
	{
		++min;
		++count;
	}
	return count * flag;
}

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

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

Date.h
#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include <iostream>
using namespace std;

class Date
{
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& _cin, Date& d);
public:
	Date(int year = 0, int month = 0, int day = 0);
	void Print();
	int GetMonthDay(int year, int month);

	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);
	bool operator!=(const Date& d);

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

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

	Date operator++();
	// d1++; 后置为了跟前置++进行区分
	// 增加了参数占位,跟前置++,构成函数重载
	Date operator++(int);
	Date& operator--();
	Date operator--(int);

	// aimDay - today
	int operator-(const Date& d);

	int PrintWeekDay()
	{
		const char* arr[] = { "星期1","星期2" ,"星期3" ,"星期4" ,"星期5" ,"星期7","星期7" };
		Date start(1900, 1, 1);
		int count = *this - start;
		cout << arr[count % 7] << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玄澈_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值