C++类和对象(中)

类的默认成员函数

默认成员函数就是用户没有显式实现,编译器会自动生成的成员函数。一个类,我们不写的情况下编译器会默认生成6个默认成员函数,C++11以后还会增加两个默认成员函数,移动构造和移动赋值。默认成员函数 很重要,也比较复杂,我们要从两个方面去学习:

第⼀:我们不写时,编译器默认⽣成的函数⾏为是什么,是否满⾜我们的需求?
第二:编译器默认⽣成的函数不满⾜我们的需求,我们需要⾃⼰实现,那么如何⾃⼰实现?

构造函数

构造函数是特殊的成员函数,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象(我们常使⽤的局部对象是栈帧创建时,空间就开好了),⽽是对象实例化时初始化对象。构造函数的本质是要替代我们以前Stack和Date类中写的Init函数的功能,构造函数⾃动调⽤的特点就完美的替代的了Init。

构造函数的特点:

  1. 函数名与类名相同。
  2. ⽆返回值。(返回值啥都不需要给,也不需要写void,不要纠结,C++规定如此)
  3. 对象实例化时系统会⾃动调⽤对应的构造函数。
  4. 构造函数可以重载。
  5. 如果类中没有显式定义构造函数,则C++编译器会⾃动⽣成⼀个⽆参的默认构造函数,⼀旦用户显式定义编译器将不再⽣成。
  6. 我们不写,编译器默认⽣成的构造,对内置类型成员变量的初始化没有要求,也就是说是否初始化是不确定的,看编译器。对于⾃定义类型成员变量,要求调⽤这个成员变量的默认构造函数初始化。如果这个成员变量没有默认构造函数,那么就会报错。
  7. ⽆参构造函数、全缺省构造函数、我们不写构造时编译器默认⽣成的构造函数,都叫做默认构造函数。但是这三个函数有且只有⼀个存在,不能同时存在。⽆参构造函数和全缺省构造函数虽然构成函数重载,但是调⽤时会存在歧义。要注意很多人会认为默认构造函数是编译器默认⽣成那个叫默认构造,实际上⽆参构造函数、全缺省构造函数也是默认构造,总结⼀下就是不传实参就可以调⽤的构造就叫默认构造。

说明:C++把类型分成内置类型(基本类型)和⾃定义类型。内置类型就是语⾔提供的原⽣数据类型, 如:int / char / double / 指针等,⾃定义类型就是我们使⽤class / struct等关键字⾃⼰定义的类型。

cpp 复制代码
#include <iostream>
using namespace std;

class Date
{
public:
	//无参构造函数
	Date()
	{
		_year = 1;
		_month = 1;
		_day = 1;
	}
	//带参构造函数
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	//全缺省构造函数
	//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 d1;//调用默认构造函数
	d1.Print();

	Date d2(2023, 2, 2);//调用带参的构造函数
	d2.Print();

	//注意:如果通过⽆参构造函数创建对象时,对象后⾯不⽤跟括号,
	//否则编译器⽆法区分这⾥是函数声明还是实例化对象。
	//warning C4930: "Date d3(void)": 未调用原型函数(是否是有意用变量定义的?)
	//Date d3(); //-> Date func(); 这样就看着像函数声明了 

	return 0;
}
cpp 复制代码
#include<iostream>
using namespace std;

typedef int STDataType;
class Stack
{
public:
	//全缺省构造函数
	Stack(int n = 4)
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (nullptr == _a)
		{
			perror("malloc fail");
			return;
		}
		_capacity = n;
		_top = 0;
		
		//打印证明确实调用了构造函数
		cout << "Stack(int n = 4)" << endl;
	}
	// ...
private:
	STDataType* _a;
	int _capacity;
	int _top;
};

// 两个Stack实现队列
class MyQueue
{
public:
	//编译器默认⽣成MyQueue的构造函数调⽤了Stack的构造,完成了两个成员的初始化

private:
	Stack pushst;
	Stack popst;
};
int main()
{
	MyQueue mq;
	return 0;
}

析构函数

析构函数与构造函数功能相反,析构函数不是完成对对象本⾝的销毁,⽐如局部对象是存在栈帧的,函数结束栈帧销毁,他就释放了,不需要我们管,C++规定对象在销毁时会⾃动调⽤析构函数,完成对象中资源的清理释放⼯作。析构函数的功能类⽐我们之前Stack实现的Destroy功能,⽽像Date没有Destroy,其实就是没有资源需要释放,所以严格说Date是不需要析构函数的。

析构函数的特点:

  1. 析构函数名是在类名前加上字符~。
  2. ⽆参数⽆返回值。(这⾥跟构造类似,也不需要加void,但是多了一个无参)
  3. ⼀个类只能有⼀个析构函数。若未显式定义,系统会⾃动⽣成默认的析构函数。
  4. 对象⽣命周期结束时,系统会⾃动调⽤析构函数。
  5. 跟构造函数类似,我们不写编译器⾃动⽣成的析构函数对内置类型成员不做处理,自定义类型成员会调⽤他的析构函数。
  6. 注意:我们显式写析构函数,对于⾃定义类型成员也会调⽤他的析构,也就是说⾃定义类型成员⽆论什么情况都会⾃动调⽤析构函数。
  7. 如果类中没有申请资源时,析构函数可以不写,直接使⽤编译器⽣成的默认析构函数,如Date; 如果默认⽣成的析构就可以⽤,也就不需要显式写析构,如MyQueue;但是有资源申请时,⼀定要⾃⼰写析构,否则会造成资源泄漏,如Stack。
  8. ⼀个局部域的多个对象,C++规定后定义的对象先析构。
cpp 复制代码
#include<iostream>
using namespace std;

typedef int STDataType;
class Stack
{
public:
	//全缺省构造函数
	Stack(int n = 4)
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (nullptr == _a)
		{
			perror("malloc fail");
			return;
		}
		_capacity = n;
		_top = 0;

		//打印证明确实调用了构造函数
		cout << "Stack(int n = 4)" << endl;
	}
	//析构函数
	~Stack()
	{
		free(_a);
		_a = nullptr;
		_capacity = _top = 0;

		//打印证明确实调用了析构函数
		cout << "~Stack()" << endl;
	}
private:
	STDataType* _a;
	int _capacity;
	int _top;
};

// 两个Stack实现队列
class MyQueue
{
public:
	//编译器默认⽣成MyQueue的析构函数调⽤了Stack的析构,释放的Stack内部的资源

	//显式写析构,也会⾃动调⽤Stack的析构
	//6. 我们显式写析构函数,对于⾃定义类型成员也会调⽤他的析构,也就是说⾃定义类
	//型成员⽆论什么情况都会⾃动调⽤析构函数。
	//~MyQueue()
	//{}
private:
	Stack pushst;
	Stack popst;
};
int main()
{
	MyQueue mq;
	return 0;
}

拷贝构造函数

如果⼀个构造函数的第⼀个参数是⾃⾝类类型的引⽤,且任何额外的参数都有默认值,则此构造函数也叫做拷⻉构造函数,也就是说拷⻉构造是⼀个特殊的构造函数。

拷贝构造的特点:

  1. 拷⻉构造函数是构造函数的⼀个重载。
  2. 拷⻉构造函数的第⼀个参数必须是类类型对象的引⽤,使⽤传值⽅式编译器直接报错,因为语法逻辑上会引发⽆穷递归调⽤。拷⻉构造函数也可以多个参数,但是第⼀个参数必须是类类型对象的引⽤,后⾯的参数必须有缺省值。
  3. C++规定⾃定义类型对象进⾏拷⻉⾏为必须调⽤拷⻉构造,所以这⾥⾃定义类型传值传参和传值返回都会调⽤拷⻉构造完成。
  4. 若未显式定义拷⻉构造,编译器会⽣成⾃动⽣成拷⻉构造函数。⾃动⽣成的拷⻉构造对内置类型成员变量会完成值拷⻉ / 浅拷⻉(⼀个字节⼀个字节的拷⻉),对⾃定义类型成员变量会调⽤他的拷⻉构造。
  5. 像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器⾃动⽣成的拷⻉构造就可以完成需要的拷⻉,所以不需要我们显式实现拷⻉构造。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器⾃动⽣成的拷⻉构造完成的值拷⻉ / 浅拷⻉不符合我们的需求,所以需要我们⾃⼰实现深拷⻉(对指向的资源也进⾏拷⻉)。像MyQueue这样的类型内部主要是⾃定义类型Stack成员,编译器⾃动⽣成的拷⻉构造会调⽤Stack的拷⻉构造,也不需要我们显式实现MyQueue的拷⻉构造。这⾥还有⼀个⼩技巧,如果⼀个类显式实现了析构并释放资源,那么他就需要显式写拷⻉构造,否则就不需要。
  6. 传值返回会产⽣⼀个临时对象调⽤拷⻉构造,传引⽤返回,返回的是返回对象的别名(引⽤),没有产⽣拷⻉。但是如果返回对象是⼀个当前函数局部域的局部对象,函数结束就销毁了,那么使⽤引⽤返回是有问题的,这时的引⽤相当于⼀个野引⽤,类似⼀个野指针⼀样。传引⽤返回可以减少拷⻉,但是⼀定要确保返回对象在当前函数结束后还在,才能⽤引⽤返回。
cpp 复制代码
#include<iostream>
using namespace std;

class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	//拷贝构造
	//d2(d1)
	Date(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}

	//普通拷贝,不是拷贝构造
	Date(const Date* d)
	{
		_year = d->_year;
		_month = d->_month;
		_day = d->_day;
	}
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

//形参是实参的一份临时拷贝,自定义类型拷贝要调用拷贝构造
//所以拷贝构造第一个参数如果不引用的话就会一直调用无限递归
void Func1(Date d)
{
	cout << &d << endl;
	d.Print();
}

//Date Func2()
Date& Func2()
{
	Date tmp(2021, 2, 4);
	tmp.Print();

	return tmp;
}

int main()
{
	Date d1(2024, 4, 25); //构造
	Date d2(d1);  //拷贝构造 
	Date d2 = d1; //相当于Date d2(d1);
	//C++规定⾃定义类型对象进⾏拷⻉⾏为必须调⽤拷⻉构造,所以这⾥传值传参要调⽤拷⻉构造
	//所以这⾥的d2传值传参给d1要调⽤拷⻉构造完成拷⻉,传引⽤传参可以较少这⾥的拷⻉
	//Func1(d1);
	//d1.Print();
	//d2.Print();

	//这⾥可以完成拷⻉,但是不是拷⻉构造,只是⼀个普通的构造
	//Date d3(&d1);
	//d1.Print();
	//d3.Print();

	// Func2返回了⼀个局部对象tmp的引⽤作为返回值
	// Func2函数结束,tmp对象就销毁了,相当于了⼀个野引⽤
	Date ret = Func2();
	ret.Print();

	return 0;
}
cpp 复制代码
#include<iostream>
using namespace std;

typedef int STDataType;
class Stack
{
public:
	//默认构造
	Stack(int n = 4)
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (nullptr == _a)
		{
			perror("malloc fail");
			return;
		}
		_capacity = n;
		_top = 0;
	}
	//拷贝构造
	//st2(st1)
	Stack(const Stack& s)
	{
		//需要对_a指向资源创建同样⼤的资源再拷⻉值
		_a = (STDataType*)malloc(sizeof(STDataType) * s._capacity);
		if (nullptr == _a)
		{
			perror("malloc fail");
			return;
		}
		memcpy(_a, s._a, sizeof(STDataType) * s._top);
		_capacity = s._capacity;
		_top = s._top;
	}
	void Push(int x)
	{
		//扩容
		//...
		_a[_top++] = x;
	}
	//析构
	~Stack()
	{
		free(_a);
		_a = nullptr;
		_capacity = _top = 0;
	}
private:
	STDataType* _a;
	int _capacity;
	int _top;
};

// 两个Stack实现队列
class MyQueue
{
public:

private:
	Stack pushst;
	Stack popst;
};

int main()
{
	Stack st1;
	st1.Push(1);
	st1.Push(2);
	st1.Push(3);
	st1.Push(4);
	//Stack不显式实现拷⻉构造,⽤⾃动⽣成的拷⻉构造完成浅拷⻉
	//会导致st1和st2⾥⾯的_a指针指向同⼀块资源,析构时会析构两次,程序崩溃
	Stack st2 = st1;//Stack st2(st1);

	MyQueue mq1;
	//MyQueue⾃动⽣成的拷⻉构造,会⾃动调⽤Stack拷⻉构造完成pushst / popst
	//的拷⻉,只要Stack拷⻉构造⾃⼰实现了深拷⻉,他就没问题

	MyQueue mq2 = mq1;

	return 0;
}

赋值运算符重载

运算符重载

  1. 当运算符被⽤于类类型的对象时,C++语⾔允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象使⽤运算符时,必须转换成调⽤对应运算符重载,若没有对应的运算符重载,则会编译报错。
  2. 运算符重载是具有特殊名字的函数,他的名字是由operator和后⾯要定义的运算符共同构成。和其他函数⼀样,它也具有其返回类型和参数列表以及函数体。
  3. 重载运算符函数的参数个数和该运算符作⽤的运算对象数量⼀样多。⼀元运算符有⼀个参数,⼆元运算符有两个参数,⼆元运算符的左侧运算对象传给第⼀个参数,右侧运算对象传给第⼆个参数。
  4. 如果⼀个重载运算符函数是成员函数,则它的第⼀个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数⽐运算对象少⼀个。
  5. 运算符重载以后,其优先级和结合性与对应的内置类型运算符保持⼀致。
  6. 不能通过连接语法中没有的符号来创建新的操作符:⽐如operator@。
  7. .* :: sizeof ?: . 注意以上5个运算符不能重载。
  8. 重载操作符⾄少有⼀个类类型参数,不能通过运算符重载改变内置类型对象的含义,
    如:operator+(int x, int y)
  9. ⼀个类需要重载哪些运算符,是看哪些运算符重载后有意义,⽐如Date类重载operator - 就有意义,但是重载operator * 就没有意义。
  10. 重载++运算符时,有前置++和后置++,运算符重载函数名都是operator++,⽆法很好的区分。 C++规定,后置++重载时,增加⼀个int形参,跟前置++构成函数重载,⽅便区分。
  11. 重载 << 和 >> 时,需要重载为全局函数,因为重载为成员函数,this指针默认抢占了第⼀个形参位 置,第⼀个形参位置是左侧运算对象,调⽤时就变成了对象 << cout,不符合使⽤习惯和可读性。 重载为全局函数把ostream / istream放到第⼀个形参位置就可以了,第⼆个形参位置为类类型对象。
cpp 复制代码
#include <iostream>
using namespace std;

//error C2803: "operator +"必须至少有一个类类型的形参
//int operator+(int x, int y)
//{
//	return x + y;
//}

class A
{
public:
	void func()
	{
		cout << "void func()" << endl;
	}
};

void func1()
{
	cout << "void func1()" << endl;
}

int main()
{
	void(*pf1)() = func1; //函数指针
	pf1();//利用函数指针调用函数

	//C++规定成员函数要加&才能取到成员指针
	void(A::*pf)() = &A::func;//成员函数指针
	A tmp;
	//对象调用成员函数指针时,使用.*运算符
	(tmp.*pf)();

	return 0;
}
cpp 复制代码
#include <iostream>
using namespace std;

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

//重载为全局的运算符重载函数,⾯临对象访问私有成员变量的问题
//有⼏种⽅法可以解决:
//1、成员放公有
//2、Date提供getxxx函数
//3、友元函数
//4、重载为成员函数
bool operator==(const Date& x1, const Date& x2)
{
	return x1._year == x2._year
		&& x1._month == x2._month
		&& x1._day == x2._day;
}

int main()
{
	Date d1(2024, 4, 3);
	Date d2 = d1;

	//bool ret = d1 == d2; //编译器会转换成operator==(d1, d2);
	bool ret = operator==(d1, d2);//运算符重载函数可以显式调⽤
	cout << ret << endl;
	return 0;
}

Date.h

cpp 复制代码
#pragma once
#include <iostream>
#include <cassert>
using namespace std;

class Date
{
public:
	//友元函数声明
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);

	bool CheckDate();//日期是否非法检查
	void Print();

	Date(int year = 1, int month = 1, int day = 1);

	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;

	//直接定义类⾥⾯,他默认是inline,频繁调⽤
	//得到每月的天数
	int GetDay(int year, int month)
	{
		assert(year > 0 && month > 0 && month < 13);
		static int Month[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

		if (month == 2 && ((year % 100 != 0 && year % 4 == 0) || year % 400 == 0))
			return 29;
		else
			return Month[month];
	}
	
	//日期 += 天数
	Date& operator+=(int day);
	//日期 + 天数
	Date operator+(int day);
	//日期 -= 天数
	Date& operator-=(int day);
	//日期 - 天数
	Date operator-(int day);

	Date& operator++();//前置
	Date operator++(int);//后置
	Date& operator--();
	Date operator--(int);
	
	//日期 - 日期
	int operator-(const Date& d);

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

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

Date.cpp

cpp 复制代码
#include "Date.h"

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

bool Date::CheckDate()
{
	if (_month < 1 || _month > 12 || _year < 1
		|| _day < 1 || _day > GetDay(_year, _month))
		return false;
	else
		return true;
}

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

	//if (!this->CheckDate())
	if (!CheckDate())
		cout << "日期非法->" << *this << endl;
}

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

bool Date::operator>(const Date& d)
{
	if (_year != d._year)
		return _year > d._year;
	else if (_month != d._month)
		return _month > d._month;
	else
		return _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);
}

Date& Date::operator+=(int day)
{
	if (day < 0)
		return *this -= -day;

	_day += day;
	while (_day > GetDay(_year, _month))
	{
		_day -= GetDay(_year, _month);
		_month++;
		if (_month > 12)
		{
			_year++;
			_month = 1;
		}
	}
	return *this;
}

Date Date::operator+(int day)
{
	Date tmp = *this;
	tmp += day;
	return tmp;
	//Date tmp = *this;
	//tmp._day += day;
	//while (tmp._day > GetDay(tmp._year, tmp._month))
	//{
	//	tmp._day -= GetDay(tmp._year, tmp._month);
	//	tmp._month++;
	//	if (tmp._month > 12)
	//	{
	//		tmp._year++;
	//		tmp._month = 1;
	//	}
	//}
	//return tmp;
}

Date& Date::operator-=(int day)
{
	if (day < 0)
		return *this += -day;

	_day -= day;
	while (_day <= 0)
	{
		if (_month == 1)
		{
			_month = 13;
			_year--;
		}
		_day += GetDay(_year, _month - 1);
		_month--;
	}
	return *this;
}

Date Date::operator-(int day)
{
	Date tmp = *this;
	tmp -= day;
	return tmp;
	//Date tmp = *this;
	//tmp._day -= day;
	//while (tmp._day <= 0)
	//{
	//	if (tmp._month == 1)
	//	{
	//		tmp._month = 13;
	//		tmp._year--;
	//	}
	//	tmp._day += GetDay(tmp._year, tmp._month - 1);
	//	tmp._month--;
	//}
	//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;
}

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 cnt = 0;
	while (min != max)
	{
		++min;
		++cnt;
	}
	return cnt * flag;
}

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)
	{
		cout << "请依次输入年月日:";
		in >> d._year >> d._month >> d._day;
		if (!d.CheckDate())
			cout << "非法日期,请重新输入!" << endl;
		else
			break;
	}

	return in;
}

test.cpp

cpp 复制代码
#include "Date.h"
int main()
{
	//重载等于 ==
	//Date d1(2023, 3, 4);
	//Date d2(2023, 5, 6);
	//cout << (d1 == d2) << endl;
	
	//重载日期加等天数
	//Date d1(2025, 10, 20);
	//Date d2 = d1 += 100;
	//d1.Print();
	//d2.Print();
	
	//重载日期加天数
	//Date d1(2025, 10, 20);
	//Date d2 = d1 + 100;
	//d1.Print();
	//d2.Print();
	
	//重载大于 >
	//Date d1(2025, 10, 20);
	//Date d2(2025, 10, 21);
	//cout << (d1 > d2) << endl;
	
	//重载日期减天数
	//Date d1(2025, 1, 20);
	//Date d2 = d1 - 100;
	//d1.Print();
	//d2.Print();
	
	//重载日期减等天数
	//Date d1(2025, 4, 26);
	//Date d2 = d1 -= -1000;
	//d1.Print();
	//d2.Print();

	//重载前置后置加加 ++
	//Date d1(2025, 4, 26);
	//Date d2 = ++d1;
	//d1.Print();
	//d2.Print();
	//cout << endl;
	//Date d3(2025, 4, 26);
	//Date d4 = d3++;
	//d3.Print();
	//d4.Print();
	
	//重载前置后置减减 --
	//Date d1(2025, 4, 26);
	//Date d2 = --d1;
	//d1.Print();
	//d2.Print();
	//cout << endl;
	//Date d3(2025, 4, 26);
	//Date d4 = d3--;
	//d3.Print();
	//d4.Print();

	//重载日期 - 日期
	//Date d1(1979, 6, 3);
	//Date d2(2006, 7, 3);
	//cout << d2 - d1 << endl;
	
	//重载<< 
	//将其放在类中重载为成员函数的情况
	//Date d1(2025, 4, 26);
	//Date d2(2025, 10, 21);
	//d1 << cout;
	//d1.operator<<(cout);
	
	//重载 << 和 >>
	//利用友元函数
	Date d1(2025, 4, 26);
	Date d2(2025, 10, 21);
	cout << d1 << d2 << endl;
	operator<<(cout, d1);
	operator<<(cout, d2);
	cin >> d1 >> d2;
	cout << d1 << d2 << endl;


	return 0;
}

赋值运算符重载

赋值运算符重载是⼀个默认成员函数,⽤于完成两个已经存在的对象直接的拷⻉赋值,这⾥要注意跟拷⻉构造区分,拷⻉构造⽤于⼀个对象拷⻉初始化给另⼀个要创建的对象。

赋值运算符重载的特点:

  1. 赋值运算符重载是⼀个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成 const 当前类类型引⽤,否则会传值传参会有拷⻉。
  2. 有返回值,且建议写成当前类类型引⽤,引⽤返回可以提⾼效率,有返回值⽬的是为了⽀持连续赋值场景。
  3. 没有显式实现时,编译器会⾃动⽣成⼀个默认赋值运算符重载,默认赋值运算符重载⾏为跟默认拷⻉构造函数类似,对内置类型成员变量会完成值拷⻉ / 浅拷⻉(⼀个字节⼀个字节的拷⻉),对⾃定义类型成员变量会调⽤他的赋值重载函数。
    4.像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器⾃动⽣成的赋值运算符重载就可以完成需要的拷⻉,所以不需要我们显式实现赋值运算符重载。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器⾃动⽣成的赋值运算符重载完成的值拷⻉ / 浅拷⻉不符合我们的需求,所以需要我们⾃⼰实现深拷⻉(对指向的资源也进⾏拷⻉)。像MyQueue这样的类型内部主要是⾃定义类型Stack成员,编译器⾃动⽣成的赋值运算符重载会调⽤Stack的赋值运算符重载,也不需要我们显式实现MyQueue的赋值运算符重载。这⾥还有⼀个⼩技巧,如果⼀个类显式实现了析构并释放资源,那么他就需要显式写赋值运算符重载,否则就不需要。

Date.h的Date类中

cpp 复制代码
Date& operator=(const Date& d);

Date.cpp中

cpp 复制代码
Date& Date::operator=(const Date& d)
{
	if (*this != d) //如果是d1 = d1就是自己给自己赋值的情况,直接跳过该逻辑
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}

	return *this;
}

test.cpp中

cpp 复制代码
int main()
{
	Date d1(2025, 4, 26);
	//⼀个对象拷⻉初始化给另⼀个要创建的对象
	Date d2 = d1; //拷贝构造

	Date d3(2024, 1, 22);
	//两个已经存在的对象直接的拷⻉赋值
	d1 = d3; //赋值运算符重载
	d1 = d1;//自己给自己赋值
	d1 = d2 = d3;//连续赋值
	return 0;
}

取地址运算符重载

const成员函数

  1. 将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后⾯。
  2. const实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进⾏修改。 const 修饰Date类的Print成员函数,Print隐含的this指针由 Date* const this变为const Date* const this

Date.h

cpp 复制代码
	//只要不改变调用对象的函数都建议加const
	//void Print(const Date* const this) const;
	void Print() const;

Date.cpp

cpp 复制代码
void Date::Print() const
{
	cout << _year << "/" << _month << "/" << _day << endl;
}

总结:只要不改变调用对象的函数都建议加const,比如日期类中的日期加天数、日期减日期、比较大小的运算符重载等等都不改变调用对象,下面日期类的全部代码里能加const的基本都加了。

取地址运算符重载

取地址运算符重载分为普通取地址运算符重载和const取地址运算符重载,⼀般这两个函数编译器⾃动⽣成的就可以够我们⽤了,不需要去显式实现。除⾮⼀些很特殊的场景,⽐如我们不想让别⼈取到当前类对象的地址,就可以⾃⼰实现⼀份,胡乱返回⼀个地址。

Date.h

cpp 复制代码
	//取地址运算符重载
	Date* operator&()
	{
		//return this; //默认是这样写的
		//return nullptr; //让对方取到空地址
		return (Date*)0x0012ff40; //让对方取到我们随便编的地址
	}

	const Date* operator&() const
	{
		//return this;
		//return nullptr;
		return (const Date*)0x135222ff;
	}

test.cpp

cpp 复制代码
int main()
{
	Date d1;
	const Date d2;

	cout << &d1 << endl;
	cout << &d2 << endl;

	return 0;
}

日期类全部代码

Date.h

cpp 复制代码
#pragma once
#include <iostream>
#include <cassert>
using namespace std;

class Date
{
public:
	//友元函数声明
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);

	bool CheckDate();

	//只要不改变调用对象的函数都建议加const
	//void Print(const Date* const this) const;
	void Print() const;

	Date(int year = 1, int month = 1, int day = 1);

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

	//直接定义类⾥⾯,他默认是inline,频繁调⽤
	int GetDay(int year, int month)
	{
		assert(year > 0 && month > 0 && month < 13);
		static int Month[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

		if (month == 2 && ((year % 100 != 0 && year % 4 == 0) || year % 400 == 0))
			return 29;
		else
			return Month[month];
	}

	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;

	//取地址运算符重载
	Date* operator&()
	{
		//return this;
		//return nullptr;
		return (Date*)0x0012ff40;
	}

	const Date* operator&() const
	{
		//return this;
		//return nullptr;
		return (const Date*)0x135222ff;
	}

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

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

Date.cpp

cpp 复制代码
#include "Date.h"

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

bool Date::CheckDate()
{
	if (_month < 1 || _month > 12 || _year < 1
		|| _day < 1 || _day > GetDay(_year, _month))
		return false;
	else
		return true;
}

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

	//if (!this->CheckDate())
	if (!CheckDate())
		cout << "日期非法->" << *this << endl;
}

//Date& Date::operator=(const Date& d)
//{
//	if (*this != d) //如果是 d1 = d1 的情况,直接跳过该逻辑
//	{
//		_year = d._year;
//		_month = d._month;
//		_day = d._day;
//	}
//
//	return *this;
//}

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

bool Date::operator>(const Date& d) const
{
	if (_year != d._year)
		return _year > d._year;
	else if (_month != d._month)
		return _month > d._month;
	else
		return _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);
}

Date& Date::operator+=(int day)
{
	if (day < 0)
		return *this -= -day;

	_day += day;
	while (_day > GetDay(_year, _month))
	{
		_day -= GetDay(_year, _month);
		_month++;
		if (_month > 12)
		{
			_year++;
			_month = 1;
		}
	}
	return *this;
}

Date Date::operator+(int day) const
{
	Date tmp = *this;
	tmp += day;
	return tmp;
	//Date tmp = *this;
	//tmp._day += day;
	//while (tmp._day > GetDay(tmp._year, tmp._month))
	//{
	//	tmp._day -= GetDay(tmp._year, tmp._month);
	//	tmp._month++;
	//	if (tmp._month > 12)
	//	{
	//		tmp._year++;
	//		tmp._month = 1;
	//	}
	//}
	//return tmp;
}

Date& Date::operator-=(int day)
{
	if (day < 0)
		return *this += -day;

	_day -= day;
	while (_day <= 0)
	{
		if (_month == 1)
		{
			_month = 13;
			_year--;
		}
		_day += GetDay(_year, _month - 1);
		_month--;
	}
	return *this;
}

Date Date::operator-(int day) const
{
	Date tmp = *this;
	tmp -= day;
	return tmp;
	//Date tmp = *this;
	//tmp._day -= day;
	//while (tmp._day <= 0)
	//{
	//	if (tmp._month == 1)
	//	{
	//		tmp._month = 13;
	//		tmp._year--;
	//	}
	//	tmp._day += GetDay(tmp._year, tmp._month - 1);
	//	tmp._month--;
	//}
	//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;
}

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 cnt = 0;
	while (min != max)
	{
		++min;
		++cnt;
	}
	return cnt * flag;
}

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)
	{
		cout << "请依次输入年月日:";
		in >> d._year >> d._month >> d._day;
		if (!d.CheckDate())
			cout << "非法日期,请重新输入!" << endl;
		else
			break;
	}

	return in;
}
相关推荐
虾球xz几秒前
游戏引擎学习第250天:# 清理DEBUG GUID
c++·学习·游戏引擎
martian6651 分钟前
信创系统图形界面开发指南:技术选择与实践详解
开发语言·科技·系统架构·系统安全·创业创新
我命由我123452 分钟前
STM32 开发 - stm32f10x.h 头文件(内存映射、寄存器结构体与宏、寄存器位定义、实现点灯案例)
c语言·开发语言·c++·stm32·单片机·嵌入式硬件·嵌入式
ghost14325 分钟前
C#学习第20天:垃圾回收
开发语言·学习·c#
oioihoii31 分钟前
C++23 std::invoke_r:调用可调用 (Callable) 对象 (P2136R3)
开发语言·c++23
一眼青苔43 分钟前
conda添加新python版本环境,如何激活和销毁
开发语言·python·conda
Pseudo…1 小时前
web技术与Nginx网站服务
开发语言·php
淋过很多场雨1 小时前
现代c++获取linux所有的网络接口名称
java·linux·c++
咛辉1 小时前
spark和Hadoop之间的对比和联系
开发语言
Humbunklung1 小时前
Sigmoid函数简介及其Python实现
开发语言·python·深度学习·机器学习