【C++详解】——类和对象(中)(默认成员函数、日期类的实现)

📖 前言:本期我们将进入类和对象的中篇——相关默认成员函数。


🕒 1. 类的6个默认成员函数

在一个空类当中,是真的没有任何成员吗?并不是,空类当中会生成6个默认函数。
默认成员函数是特殊成员函数,也就是我们不写,编译器会自己生成一个;我们自己写了,编译器就不会生成。
默认成员函数不会显示地展示给我们看,而是编译器自动生成的隐式的成员函数。

在这里插入图片描述

🕒 2. 构造函数(constructor)

🕘 2.1 构造函数的概念

以前我们用C语言实现栈的时候,经常会忘记InitDestroy,造成内存泄漏。那有没有一种可能,我们可以让编译器自动加上呢?于是C++就带来了构造函数。

class Date
{
public:
	/*void Init(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}*/

	void Print()
	{
		cout << _year << "_" << _month << "_" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1, d2;
	//d1.Init(2022, 10, 5);
	//d2.Init(2022, 11, 11);
	d1.Print();
	d2.Print();
	return 0;
}

还是我们的日期类,我们假定忘记了Init ,那能不能在对象定义的时候就初始化呢?

构造函数是一个特殊的成员函数,名字与类名相同,创建类类型对象时由编译器自动调用,以保证每个数据成员都有一个合适的初始值,并且在对象整个生命周期内只调用一次。
需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象,而是初始化对象

🕘 2.2 特性

  1. 函数名与类名相同。
  2. 无返回值。(void都没有)
  3. 对象实例化时编译器自动调用对应的构造函数。
  4. 构造函数可以重载。
class Date
{
public:
	// 1.无参构造函数
	Date()
	{
		_year = 1970;
		_month = 1;
		_day = 1;
	}

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

	void Print()
	{
		cout << _year << "_" << _month << "_" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1;			// 调用无参构造函数
	Date d2(2022,10,7);	// 调用带参构造函数

	d1.Print();
	d2.Print();

	// 注意:如果通过无参构造函数创建对象时,对象后面不用跟括号,否则就成了函数声明
	// 以下代码的函数:声明了d3函数,该函数无参,返回一个日期类型的对象
	
	Date d3();	// warning C4930: “Date d3(void)”: 未调用原型函数(是否是有意用变量定义的?)	
	Date d4;	// 正确写法,避免和函数声明格式混淆

	return 0;
}

我们用缺省参数再改造一下
注:全缺省和无参语法上可以同时存在,但调用时会存在二义性,不要这么写

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

以下为正确打开方式:

	// 初始化
	Date(int year = 1970, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

在这里插入图片描述

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

  2. 关于编译器生成的默认成员函数,大家可能会有疑惑:不实现构造函数的情况下,编译器会生成默认的构造函数。但是看起来默认构造函数又没什么用?d对象调用了编译器生成的默认构造函数,但是d对象_year/_month/_day,依旧是随机值。也就说在这里编译器生成的默认构造函数并没有什么用?
    解答:C++把类型分成内置类型(基本类型)和自定义类型。内置类型就是语言提供的数据类型,如:int/char...指针,自定义类型就是我们使用class/struct/union等自己定义的类型,看看下面的程序,就会发现编译器生成默认的构造函数会对自定类型成员_aa调用的它的默认成员函数。

举个例子:

// example 1:
class Date
{
public:
	// 初始化	(如果用户显式定义了构造函数,编译器将不再生成)
	//Date(int year = 1, int month = 1, int day = 1)
	//{
	//	_year = year;
	//	_month = month;
	//	_day = day;
	//}

	void Print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

private:
	// 内置类型
	int _year;     // 年
	int _month;    // 月
	int _day;      // 日
};

int main()
{
	// 将Date类中构造函数屏蔽后,代码可以通过编译,因为编译器生成了一个无参的默认构造函数
	// 将Date类中构造函数放开,代码编译失败,因为一旦显式定义任何构造函数,编译器将不再生成
	// 无参构造函数,放开后报错:error C2512: “Date”: 没有合适的默认构造函数可用
	Date d1;	
	d1.Print();		// 输出:-858993460--858993460--858993460
	
	return 0;
}

可以看到,由编译器生成了构造函数后,输出的内置类型值变成了随机值,接下来看看加上自定义类型会怎么样。

// example 2:
class A
{
public:
	A()
	{
		_a = 0;
		cout << "A()构造函数" << endl;
	}
private:
	int _a;
};

class Date
{
public:
	// 初始化	(如果用户显式定义了构造函数,编译器将不再生成)
	//Date(int year = 1, int month = 1, int day = 1)
	//{
	//	_year = year;
	//	_month = month;
	//	_day = day;
	//}

	void Print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

private:
	// 内置类型
	int _year;     // 年
	int _month;    // 月
	int _day;      // 日

	// 自定义类型
	A _aa;
};

int main()
{
	// 将Date类中构造函数屏蔽后,代码可以通过编译,因为编译器生成了一个无参的默认构造函数
	// 将Date类中构造函数放开,代码编译失败,因为一旦显式定义任何构造函数,编译器将不再生成
	// 无参构造函数,放开后报错:error C2512: “Date”: 没有合适的默认构造函数可用
	Date d1;	
	d1.Print();

	return 0;
}

在这里插入图片描述

可以看到,编译器对自定义类型做了处理,而对内置类型不作处理。
在这里插入图片描述
需要注意的是,有些高版本的VS(如22版),可能会一起处理,现阶段学习我们要当成不处理。

那这有什么作用呢,别急,我们先引入析构函数的概念后再解答。

🕒 3. 析构函数(destructor)

🕘 3.1 析构函数的概念

通过前面构造函数的学习,我们知道一个对象是怎么来的,那一个对象又是怎么没的呢?
析构函数:与构造函数功能相反,析构函数不是完成对对象本身的销毁,局部对象销毁工作是由编译器完成的。而对象在销毁时会自动调用析构函数,完成对象中资源的清理工作,和destory功能相似。

🕘 3.2 特性

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

学到这里我们就可以动手改造一下之前学到栈和队列的实现

class Stack
{
public:
	Stack(int capacity = 4)	// 构造函数
	{
		cout << "Stack(int capacity = 4)" << endl;

		_a = (int*)malloc(sizeof(int) * capacity);
		if (_a == nullptr)
		{
			perror("malloc fail");
			exit(-1);
		}

		_top = 0;
		_capacity = capacity;
	}

	~Stack()	// 析构函数
	{
		cout << "~Stack()" << endl;

		free(_a);
		_a = nullptr;	// C++关键字
		_top = _capacity = 0;
	}

	void Push(int x)
	{
		// ....
		// 扩容
		_a[_top++] = x;
	}

private:
	int* _a;
	int _top;
	int _capacity;
};

int main()
{

	Stack st;
	st.Push(1);
	st.Push(2);
	st.Push(3);

	return 0;
}

前面我们挖了个坑,对于构造函数的自定义类型,我们以🔎 用栈实现队列这道题目解释

class MyQueue {
public:
	void push(int x)
	{
		_pushST.Push(x);	//这里需要写构造函数吗?不用的,默认生成的够用
	}

	Stack _pushST;
	Stack _popST;

	//size_t _size;
};

int main()
{
	MyQueue mq;
	mq.push(1);
	mq.push(2);

	return 0;
}

在这里插入图片描述
出了作用域会自动释放
在这里插入图片描述

在这里插入图片描述

调试小技巧:监视窗口输入this所有成员都能看到
在这里插入图片描述
注意:构造函数和析构函数不是完成对象的初始化和清理,即构造的时候调用构造函数初始化,析构的时候调用析构函数销毁。
此外,C++11 中针对内置类型成员不初始化的缺陷,又打了补丁,即:内置类型成员变量在类中声明时可以给默认值。
例如:

private:
	Stack _pushST;
	Stack _popST;

	size_t _size = 0;	// 这里不是初始化,给的是缺省值
};

小结:面向需求:编译器默认生成就可以满足,就不用自己写,不满足就需要自己写。 Date Stack的构造函数需要自己写,MyQueue构造函数就不需要自己写,默认生成就可以用;Stack析构函数则需要我们自己写 MyQueue,Date就不需要自己写析构函数,默认生成就可以用。

打个比方,你外卖点了顿饺子,如果附带的醋合适,也就可以直接吃了;但是如果觉得酸度不够,想要自己加点山西老陈醋,这就是自己构建构造函数。

🕒 4. 拷贝构造函数(copy constructor)

🕘 4.1 概念

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

🕘 4.2 特性

  1. 拷贝构造函数是构造函数的一个重载形式
  2. 拷贝构造函数的参数只有一个必须是类类型对象的引用,使用传值方式编译器直接报错,因为会引发无穷递归调用。
    在这里插入图片描述
    正确方式如下
class Date
{
public:

	// 初始化
	Date(int year = 1970, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	// d2(d1)
	Date(const Date& d)		// 拷贝构造函数 const防止写反
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;

		// 形参加const,防止写反了,下面问题就可以检查出来
		// d._day = _day;
	}

	void Print()
	{
		cout << _year << "_" << _month << "_" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1(2022,10,7);	// 构造 - 初始化
	d1.Print();
	// 拷贝一份d1
	Date d2(d1);	// 拷贝构造 -- 拷贝初始化
	d2.Print();

	return 0;
}
  1. 若未显式定义,编译器会生成默认的拷贝构造函数。 默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝。
    注意:在编译器生成的默认拷贝构造函数中,内置类型是按照字节方式直接拷贝的,而自定义类型是调用其拷贝构造函数完成拷贝的。

  2. 编译器生成的默认拷贝构造函数已经可以完成字节序的值拷贝了,还需要自己显式实现吗?
    当然像日期类这样的类是没必要的。那么下面的类呢?验证一下试试?

class Stack
{
public:
	Stack(int capacity = 4)
	{
		cout << "Stack(int capacity = 4)" << endl;

		_a = (int*)malloc(sizeof(int) * capacity);
		if (_a == nullptr)
		{
			perror("malloc fail");
			exit(-1);
		}

		_top = 0;
		_capacity = capacity;
	}

	~Stack()
	{
		cout << "~Stack()" << endl;

		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}

	void Push(int x)
	{
		// ....
		// 扩容
		_a[_top++] = x;
	}

private:
	int* _a;
	int _top;
	int _capacity;
};


int main()
{
	Stack st1;
	
	st1.Push(1);
	st1.Push(2);

	Stack st2(st1);

	return 0;
}

在这里插入图片描述

虽然完成了拷贝,但是并不是我们想要的。程序最终会崩溃,同一块空间析构了两次(st2先析构)。这是浅拷贝,对于一些类可以,对于一些类不可以。此时很明显,默认生成的拷贝构造函数已经不能符合我们的要求了。

正确的打开方式:深拷贝

class Stack
{
public:
	Stack(int capacity = 4)
	{
		cout << "Stack(int capacity = 4)" << endl;

		_a = (int*)malloc(sizeof(int) * capacity);
		if (_a == nullptr)
		{
			perror("malloc fail");
			exit(-1);
		}

		_top = 0;
		_capacity = capacity;
	}

	// st2(st1)
	Stack(const Stack& st)
	{
		_a = (int*)malloc(sizeof(int) * st._capacity);
		if (_a == nullptr)
		{
			perror("malloc fail");
			exit(-1);
		}
		memcpy(_a, st._a, sizeof(int) * st._top);
		_top = st._top;
		_capacity = st._capacity;
	}


	~Stack()
	{
		cout << "~Stack()" << endl;

		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}

	void Push(int x)
	{
		// ....
		// 扩容
		_a[_top++] = x;
	}

private:
	int* _a;
	int _top;
	int _capacity;
};


int main()
{
	Stack st1;
	
	st1.Push(1);
	st1.Push(2);
	// 1 2

	Stack st2(st1);
	st2.Push(10);
	// 1 2 10

	st1.Push(3);
	return 0;
}

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

小结:

  • 需要写析构函数的类,都需要写深拷贝的拷贝构造 Stack
  • 不需要写析构函数的类,默认生成的浅拷贝的拷贝构造就可以用 Date/MyQueue
  1. 拷贝构造函数典型调用场景:
  • 使用已存在对象创建新对象
  • 函数参数类型为类类型对象
  • 函数返回值类型为类类型对象

在这里插入图片描述

🕒 5. 运算符

🕘 5.1 运算符重载

C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。注意运算符重载和函数重载不是一个概念,其目的是让自定义类型对象能用运算符。
函数名字为:关键字operator后面接需要重载的运算符符号
函数原型:返回值类型 operator操作符(参数列表)
注意:

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

以日期类举例子,比如我们有需求是比较两个日期之差、n天之后是几号,判断日期相同等,该如何实现呢?

判断日期相同可以如下格式:
在这里插入图片描述
方式一:

// 全局的operator==
class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	//private:	// 暂时公有
	int _year;
	int _month;
	int _day;
};
// 这里会发现运算符重载成全局的就需要成员变量是公有的,那么问题来了,封装性如何保证?
// 这里其实可以用我们后面学习的友元解决,或者干脆重载成成员函数。
bool operator==(const Date& d1, const Date& d2)
{
	return d1._year == d2._year
		&& d1._month == d2._month
		&& d1._day == d2._day;
}
int main()
{
	Date d1(2022, 10, 11);
	Date d2(2022, 11, 11);
	cout << (d1 == d2) << endl;	// 转换成operator==(d1,d2);
	//operator == (d1, d2);	// 也可以显式调用,一般不这样是考虑到可读性
}

方式二:

// 局部的operator==
class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	//int GetYear()	// Java常用的方式 (举例)
	//{
	//	return _year;	
	//}
	
	// 放到类里面
	/*bool operator==(const Date& d1, const Date& d2)		// 这样会报错,参数太多(成员函数有个缺省参数,是this)
	{
		return d1._year == d2._year
			&& d1._month == d2._month
			&& d1._day == d2._day;
	}*/

	bool operator==(const Date& d)		// 正确方式
	{
		return d._year == d._year
			&& d._month == d._month
			&& d._day == d._day;
	}

	bool operator>(const Date& d)		// d1 > d2 的比较
	{
		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;
		}

		return false;
	}

	bool operator>=(const Date& d)		// d1 >= d2 的比较;
	{
		return *this > d || *this == d;		// 一般不加this,但这里要加
	}
	// .... < <= !=

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

int main()
{
	Date d1(2022, 10, 11);
	Date d2(2022, 11, 11);
	//cout << (d1 == d2) << endl;	// 转换成operator==(d1,d2);(全局)
	//operator == (d1, d2);	// 也可以显式调用,一般不这样是考虑到可读性

	cout << (d1 == d2) << endl;	// 转换成d1.operator==(d2);(局部)

	cout << (d1 > d2) << endl;	
	cout << (d1 >= d2) << endl;
}

日期加减呢?

class Date
{
public:
	int GetMonthDay(int year, int month)
	{
		static int monthDayArray[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;
		}
		else
		{
			return monthDayArray[month];
		}
	}


	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

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

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

		return *this;
	}

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

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


int main()
{
	Date d1(2022, 10, 11);
	Date d2(2022, 11, 11);

	d1 += 100;
}

🕘 5.2 赋值运算符重载

赋值重载既是默认成员函数,又是运算符重载

void TestDate()
{
	Date d0;
	Date d1;
	Date d2(2022, 10, 11);

	Date d3(d2);  // 拷贝构造(初始化)  一个拷贝初始化另一个马上要创建的对象
	Date d4 = d2; // 拷贝构造

	d1.Print();
	d0 = d1 = d2;      // 赋值重载(复制拷贝) 已经存在两个对象之间拷贝
	d1.Print();
}

赋值重载实现:

class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
		//检查日期是否合法
		if (!(year >= 1
			&& (month >= 1 && month <= 12)
			&& (day >= 1 && day <= GetMonthDay(year, month))))
		{
			cout << "非法日期" << endl;
		}
	}
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
	//d1 = d2;
	Date& operator = (const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
		return *this;
	}
private:
	int _year;
	int _month;
	int _day;
};
void TestDate2()
{
	Date d1;
	d1.Print();
	Date d2(2022, 10, 11);

	Date d3(d2);//拷贝构造(初始化)  一个初始化另一个马上要创建的对象
	Date d4 = d2;//拷贝构造
	 
	d1 = d2;//赋值重载(复制拷贝)     已经存在两个对象之间拷贝
	d1.Print();
}

对于赋值重载(复制拷贝)和拷贝构造的区别

  • 赋值重载(复制拷贝) 已经存在两个对象之间拷贝
  • 拷贝构造(初始化) 一个初始化另一个马上要创建的对象

赋值运算符主要有五点

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

但是如果用编译器默认的赋值运算符重载又会发生什么?(我们以栈类为例子)

class Stack
{
public:
	Stack(int capacity = 4)
	{
		cout << "Stack(int capacity = 4)" << endl;
		_a = (int*)malloc(sizeof(int) * capacity);
		if (_a == nullptr)
		{
			perror("malloc fail");
			exit(-1);
		}
		_top = 0;
		_capacity = capacity;
	}
	Stack(const Stack& st)
	{
		cout << "Stack(const Stack&st" << endl;

		_a = (int*)malloc(sizeof(int) * st._capacity);
		if (nullptr == _a)
		{
			perror("malloc fail");
			exit(-1);
		}
		memcpy(_a, st._a, sizeof(int) * st._top);
		_top = st._top;
		_capacity = st._capacity;
	}
	~Stack()
	{
		cout << "~Stack()" << endl;
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}

	void Push(int x)
	{
		_a[_top++] = x;
	}
private:
	int* _a;
	int _top;
	int _capacity;
};

void TestStack()
{
	Stack st1;
	st1.Push(1);
	st1.Push(2);

	Stack st2;
	st2.Push(3);
	st2.Push(4);
	st2.Push(5);
	st2.Push(6);

	st1 = st2;
}
int main()
{
    TestStack();
    return 0;
}

在这里插入图片描述

发生了崩溃,实际上这里的问题还是析构了两次(直接把st2的空间拷贝给st1,st1和st2的_a指向了同一个)发生了崩溃,但是此时的st1的内存还发生了泄露。栈的赋值运算符重载实现:

//st1 = st2;
//st1 = st1;
	Stack& operator = (const Stack& st)
	{
		if (this != &st)
		{
			free(_a);
			_a = (int*)malloc(sizeof(int) * st._capacity);
			if (nullptr == _a)
			{
				perror("malloc fail");
				exit(-1);
			}
			memcpy(_a, st._a, sizeof(int) * st._top);
			_top = st._top;
			_capacity = st._capacity;
		}
		return *this;
	}

在这里插入图片描述

同理,像前面用栈实现队列的例子,赋值运算符重载也不需要自己实现了。

class Stack
{
public:
	Stack(int capacity = 4)
	{
		cout << "Stack(int capacity = )" <<capacity<<endl;

		_a = (int*)malloc(sizeof(int)*capacity);
		if (_a == nullptr)
		{
			perror("malloc fail");
			exit(-1);
		}

		_top = 0;
		_capacity = capacity;
	}
	
	// st2(st1)
	Stack(const Stack& st)
	{
		cout << "Stack(const Stack& st)" << endl;

		_a = (int*)malloc(sizeof(int)*st._capacity);
		if (_a == nullptr)
		{
			perror("malloc fail");
			exit(-1);
		}
		memcpy(_a, st._a, sizeof(int)*st._top);
		_top = st._top;
		_capacity = st._capacity;
	}

	// st1 = st2;
	// st1 = st1;
	Stack& operator=(const Stack& st)
	{
		cout << "	Stack& operator=(const Stack& st)" << endl;
		if (this != &st)
		{
			free(_a);
			_a = (int*)malloc(sizeof(int)*st._capacity);
			if (_a == nullptr)
			{
				perror("malloc fail");
				exit(-1);
			}
			memcpy(_a, st._a, sizeof(int)*st._top);
			_top = st._top;
			_capacity = st._capacity;
		}

		return *this;
	}

	~Stack()
	{
		cout << "~Stack()" << endl;

		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}

	void Push(int x)
	{
		// ....
		// 扩容
		_a[_top++] = x;
	}

private:
	int* _a;
	int _top;
	int _capacity;
};

class MyQueue {
public:
	void push(int x)
	{
		_pushST.Push(x);
	}
private:
	Stack _pushST;
	Stack _popST;
	size_t _size = 0;
};

void TestStack()
{
	//Stack st1(10000);
	// 默认生成operator= 不行 需要自己实现
	Stack st1;
	st1.Push(1);
	st1.Push(2);

	Stack st2(10);
	st2.Push(10);
	st2.Push(20);
	st2.Push(30);
	st2.Push(40);

	st1 = st2;
	st1 = st1;

	// MyQueue和Date 默认生成operator= ok
	MyQueue q1;
	q1.push(1);
	q1.push(2);
	q1.push(3);

	MyQueue q2;
	q2.push(10);
	q2.push(20);
	q2.push(30);

	q1 = q2;
}

🕒 6. 流提取和流插入的重载

当我们不想使用函数在控制台对对象进行输入、输出的时候可以使用这个重载。

	Date d1(2022, 10, 11);
	cout << d1;//输出d1
	Date d2;
	cin >> d2;//输入d2

需要注意,cout和cin并不是一个函数,而是一个对象。他们两个的类型不一样。并且cout和cin都在<<和>>两个运算符的左边。所以定义为成员函数是不可取的,因为成员函数都有一个默认的隐藏的this指针作为参数。所以我们必须在类外定义这个重载函数。

方法1:把priate修饰的私有成员修改为public修饰的公有成员。

void operator<<(ostream& out, Date& d)
{
	out << d._year << "." << d._month << "." << d._day << endl;
}
void operator>>(istream& in, Date& d)
{
	in >> d._year >> d._month >> d._day;
}

那如果我们想这么实现呢?

cout << d1 << d2; // operator<<(cout,d2)
cin >> d1 >> d2;

方法如下:

ostream& operator<<(ostream& out, Date& d)
{
	out << d._year << "." << d._month << "." << d._day << endl;
	return out;
}
istream& operator>>(istream& in, Date& d)
{
	in >> d._year >> d._month >> d._day;
	return in;
}

补充:此处加上内联函数是极好的。

方法2:友元声明
我们可以在类中声明这个重载函数,并在其前加上friend关键字。

class Date
{
	friend ostream& operator<<(ostream& out, Date& d);
	friend istream& operator>>(istream& in, Date& d);	// 类的任意位置都可以
......

🕒 7. 日期类的完善实现

至此,我们对于运算符的重载也有了清晰的认识。下面,我们对日期类的运算符重载进行相关的完善补充。

Date.h

#include <iostream>
using namespace std;
class Date
{
public:
	int GetMonthDay(int year, int month)
	{
		static int monthDayArray[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;
		}
		else
		{
			return monthDayArray[month];
		}
	}

	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;

		// 检查日期是否合法
		if (!(year >= 1
			&& (month >= 1 && month <= 12)
			&& (day >= 1 && day <= GetMonthDay(year, month))))
		{
			cout << "非法日期" << endl;
		}
	}

	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}

	bool operator==(const Date& d);
	// d1 > d2
	bool operator>(const Date& d);
	// d1 >= d2
	bool operator>=(const Date& d);
	bool operator<=(const Date& d);
	bool operator<(const Date& d);
	bool operator!=(const Date& d);

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

	// d1 + 100
	Date operator+(int day);

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

	// d1 - 100
	Date operator-(int day);

	// 前置
	Date& operator++();

	// 后置
	Date operator++(int);

	// 前置
	Date& operator--();

	// 后置
	Date operator--(int);
    
    //d1 = d2;
	Date& operator = (const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
		return *this;
	}

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

Date.cpp

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

// d1 > d2
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;
	}

	return false;
}

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

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

Date& Date::operator+=(int day)
{
	if (day < 0)
	{
		//return *this -= -day;
		return *this -= abs(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)
{
	Date ret(*this);
	ret += day;
	return ret;
}

// d1 -= 100
Date& Date::operator-=(int day)
{
	if (day < 0)
	{
		//return *this -= -day;
		return *this += abs(day);
	}

	_day -= day;
	while (_day <= 0)
	{
		--_month;
		if (_month == 0)
		{
			--_year;
			_month = 12;
		}

		_day += GetMonthDay(_year, _month);
	}

	return *this;
}

// d1 - 100
Date Date::operator-(int day)
{
	Date ret(*this);
	ret -= day;

	return ret;
}

// 前置
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);	// 或者这样写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)
		//if (d > *this)
	{
		max = d;
		min = *this;
		flag = -1;
	}

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

	return n * flag;
}

test.cpp

void TestDate3()
{
	Date d1(2022, 10, 12);
	Date d2(d1);
	Date d3(d1);
	Date d4(d1);

	(++d1).Print(); // d1.operator++()
	d1.Print();

	(d2++).Print(); // d2.operator++(1)
	d2.Print();


	(--d1).Print(); // d1.operator--()
	d1.Print();

	(d2--).Print(); // d2.operator--(1)
	d2.Print();

	Date d5(2022, 10, 12);
	Date d6(2023, 9, 1);

	cout << d6 - d5 << endl;
	cout << d5 - d6 << endl;
}

在这里插入图片描述

🕒 8. 取地址及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在*之前修饰的是指针指向的对象
  • const在*之后修饰的是指针本身

OK,以上就是本期知识点“类和对象(中)”的知识啦~~ ,感谢友友们的阅读。后续还会继续更新,欢迎持续关注哟📌~
💫如果有错误❌,欢迎批评指正呀👀~让我们一起相互进步🚀
🎉如果觉得收获满满,可以点点赞👍支持一下哟~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值