当前位置: 首页 > article >正文

c++入门 类和对象(中)

文章目录

  • 1. 类的默认成员函数
  • 2. 构造函数
  • 3. 析构函数
  • 4. 拷贝构造函数
  • 5. 赋值运算符重载
    • 5.1 运算符重载
    • 5.2 赋值运算符重载
    • 5.3 日期类实现
  • 6. 取地址运算符重载
    • 6.1 const成员函数
    • 6.2 取地址运算符重载
  • 总结

1. 类的默认成员函数

默认成员函数就是用户没有显式实现,编译器会⾃动⽣成的成员函数称为默认成员函数。⼀个类,我
们不写的情况下编译器会默认⽣成以下6个默认成员函数,需要注意的是这6个中最重要的是前4个,最后两个取地址重载不重要,我们稍微了解⼀下即可。其次就是C++11以后还会增加两个默认成员函数,移动构造和移动赋值。默认成员函数很重要,也⽐较复杂,我们要从两个方面去学习:
(1).第⼀:我们不写时,编译器默认⽣成的函数行为是什么,是否满足我们的需求。
(2).第⼆:编译器默认生成的函数不满足我们的需求,我们需要自己实现,那么如何自己实现?
类的默认成员函数

2. 构造函数

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

  1. 函数名与类名相同。
  2. 无返回值。 (返回值啥都不需要给,也不需要写void,不要纠结,C++规定如此)
  3. 对象实例化时系统会自动调用对应的构造函数。
  4. 构造函数可以重载。
  5. 如果类中没有显式定义构造函数,则C++编译器会⾃动⽣成⼀个⽆参的默认构造函数,⼀旦用户显式定义编译器将不再生成。
  6. ==(1)⽆参构造函数、(2)全缺省构造函数、(3)我们不写构造时编译器默认⽣成的构造函数,都叫做默认构造函数。但是这三个函数有且只有⼀个存在,不能同时存在。==⽆参构造函数和全缺省构造函数虽然构成函数重载,但是调用时会存在歧义。要注意很多人会认为(1)默认构造函数是编译器默认生成那个叫默认构造,实际上(2)无参构造函数、(3)全缺省构造函数也是默认构造,总结⼀下就是不传实参就可以调用的构造就叫默认构造。
  7. 我们不写,编译器默认生成的构造,对内置类型成员变量的初始化没有要求,也就是说是是否初始化是不确定的,看编译器。对于自定义类型成员变量,要求调用这个成员变量的默认构造函数初始化。如果这个成员变量,没有默认构造函数,那么就会报错,我们要初始化这个成员变量,需要⽤初始化列表才能解决,初始化列表。
    说明:C++把类型分成内置类型(基本类型)和⾃定义类型。内置类型就是语⾔提供的原生数据类型,如:int/char/double/指针等,⾃定义类型就是我们使⽤class/struct等关键字自己定义的类型。
    结论:一般情况构造函数都需要自己写,少数情况,默认生成就可以使用,比如:MyQueue。
    代码中的示例和结果验证:
    (1)如果留下三个构造中的第二个代参构造,第一个和第三个注释掉,详细信息错误 C2512 “Data”: 没有合适的默认构造函数可用 9_17 。

在这里插入图片描述
(2).如果通过无参构造函数创建对象时,对象后面不用跟括号,否则编译器无法编译.区分这里是函数声明还是实例化对象 eg:Data d1() //函数声明也可以这样写,有歧义.
在这里插入图片描述
(3)如果类中没有显式定义构造函数,则C++编译器会⾃动⽣成⼀个⽆参的默认构造函数,⼀旦用户显式定义编译器将不再生成。

class Data
{
public:
	void print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
private://先写这个私密的这个对象初始化
	int _year;
	int _month;
	int _day;

};
int main()
{
	Data d1;
	d1.print();
	return 0;
}

在这里插入图片描述
(4 详细信息错误 C2512 “Data”: 没有合适的默认构造函数可用 9_17 D:\c++\c-beginners-guide\9_17\9_17\test.cpp
在这里插入图片描述
在这里插入图片描述
代码源码演示:

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class Data
{
public:
	//1.无参构造函数
	Data()
	{
		_year = 1;
		_month = 1;
		_day = 1;
	}
	//2.带参构造函数
	Data(int year,int month,int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	//3.全缺省构造函数
	/*Data(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()
{
	//如果留下三个构造中的第二个代参构造,第一个和第三个注释掉
	//错误	C2512	“Data” : 没有合适的默认构造函数可用	9_17	D : \c++\c - beginners - guide\9_17\9_17\test.cpp	98

	Data d1;   //调用默认构造函数 (不传实参的就是默认构造函数)
	Data d2(2024, 9, 18);//调用带参的构造函数
	//注意:如果通过无参构造函数创建对象时,对象后面不用跟括号,否则编译器无法编译
	//区分这里是函数声明还是实例化对象 eg:Data d1()   //函数声明也可以这样写,有歧义
	//warning C4930: “Date d3(void)”: 未调⽤原型函数(是否是有意⽤变量定义的?)
	//Data d3(void);
	Data d3();
	d1.print();
	d2.print();
	return 0;
}

(4).两个stack实现队列

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
	Stack(int  n = 4)
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (_a == NULL)
		{
			perror("malloc fail!");
			return;
		}
		_capacity = n;
		_top = 0;

	}
	//....
private:
	STDataType* _a;
	size_t _capacity;
	size_t _top;
};
//两个stack实现队列
class Mqueue
{
public:
//编译器默认生成MyQueue的构造函数调用了Stack的构造,完成两个成员的初始化
private:
	Stack pushst;
	Stack popst;
};
int main()
{
	Mqueue mq;
	return 0;
}

3. 析构函数

析构函数与构造函数功能相反,析构函数不是完成对对象本身的销毁,⽐如局部对象是存在栈帧的,函数结束栈帧销毁,他就释放了,不需要我们管,C++规定对象在销毁时会自动调⽤析构函数,完成对象中资源的清理释放⼯作。析构函数的功能类比Stack实现的Destroy功能(可以参考数据结构(初阶)satck),而像Date没有Destroy,其实就是没有资源需要释放,所以严格说Date是不需要析构函数的。
析构函数的特点:

  1. 析构函数名是在类名前加上字符 ~。
  2. ⽆参数⽆返回值。 (这里跟构造类似,也不需要加void)
  3. ⼀个类只能有⼀个析构函数。若未显式定义,系统会⾃动⽣成默认的析构函数。
	~Stack()//析构 类名前面加~
	{
		cout << "~stack()" << endl;
		free(_a);
		_a = NULL;
		_top = _capacity = 0;
	}

在这里插入图片描述

  1. 对象⽣命周期结束时,系统会自动调用析构函数。
  2. 跟构造函数类似,我们不写编译器⾃动⽣成的析构函数对内置类型成员不做处理,⾃定类型成员会调⽤他的析构函数。
  3. 还需要注意的是我们显示写析构函数,对于⾃定义类型成员也会调用他的析构,也就是说自定义类型成员⽆论什么情况都会自动调用析构函数。
	//编译器默认⽣成MyQueue的析构函数调⽤了Stack的析构,释放的Stack内部的资源
		// 显⽰写析构,也会⾃动调⽤Stack的析构
	~Myqueue()
	{}

在这里插入图片描述

  1. 如果类中没有申请资源时,析构函数可以不写,直接使⽤编译器生成的默认析构函数,如Date;如果默认⽣成的析构就可以用,也就不需要显示写析构,如MyQueue;但是有资源申请时,⼀定要自己写析构,否则会造成资源泄漏,如Stack。
  2. ⼀个局部域的多个对象,C++规定后定义的先析构。
    总结:一般情况下显示申请资源,才需要自己实现析构,其他情况基本都不需要显示写。
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
	Stack(int  n = 4)
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (_a == NULL)
		{
			perror("malloc fail!");
			return;
		}
		_capacity = n;
		_top = 0;

	}
	~Stack()//析构 类名前面加~
	{
		cout << "~stack()" << endl;
		free(_a);
		_a = NULL;
		_top = _capacity = 0;
	}
	//....
private:
	STDataType* _a;
	size_t _capacity;
	size_t _top;
};
//两个stack实现队列
class Myqueue
{
public:
//编译器默认生成MyQueue的构造函数调用了Stack的构造,完成两个成员的初始化
	//编译器默认⽣成MyQueue的析构函数调⽤了Stack的析构,释放的Stack内部的资源
		// 显⽰写析构,也会⾃动调⽤Stack的析构
	~Myqueue()
	{}
private:
	Stack pushst;
	Stack popst;
};
int main()
{
	Myqueue mq;
	return 0;
}

对比⼀下⽤C++和C实现的Stack解决之前括号匹配问题isValid,我们发现有了构造函数和析构函数确
实⽅便了很多,不会再忘记调⽤Init和Destory函数了。
部分源码:
c++版本:

#include<iostream>
using namespace std;
// ⽤最新加了构造和析构的C++版本Stack实现
bool isValid(const char* s) {
	Stack st;
	while (*s)
	{
		if (*s == '[' || *s == '(' || *s == '{')
		{
			st.Push(*s);
		}
		else
		{
			// 右括号⽐左括号多,数量匹配问题
			if (st.Empty())
			{
				return false;
			}
			// 栈⾥⾯取左括号
			char top = st.Top();
			st.Pop();
			// 顺序不匹配
			if ((*s == ']' && top != '[')
				|| (*s == '}' && top != '{')
				|| (*s == ')' && top != '('))
			{
				return false;
			}
		}
		++s;
	}
	// 栈为空,返回真,说明数量都匹配 左括号多,右括号少匹配问题
	return st.Empty();
}

int main()
{
	cout << isValid("[()][]")<<endl;
	
}

c版本:

bool isValid(const char* s) {
	ST st;
	STInit(&st);
	while (*s)
	{
		// 左括号⼊栈
		if (*s == '(' || *s == '[' || *s == '{')
		{
			STPush(&st, *s);
		}
		else // 右括号取栈顶左括号尝试匹配
		{
			if (STEmpty(&st))
			{
				STDestroy(&st);
				return false;
			}
			char top = STTop(&st);
			STPop(&st);
			// 不匹配
			if ((top == '(' && *s != ')')
				|| (top == '{' && *s != '}')
				|| (top == '[' && *s != ']'))
			{
				STDestroy(&st);
				return false;
			}
		}
		++s;
	}
	// 栈不为空,说明左括号⽐右括号多,数量不匹配
	bool ret = STEmpty(&st);
	STDestroy(&st);
	return ret;
}
int main()
{
	cout << isValid("[()][]") << endl;
	return 0;
}

4. 拷贝构造函数

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

  1. 拷贝构造函数是构造函数的⼀个重载。
  2. 拷贝构造函数的第⼀个参数必须是类类型对象的引⽤,使⽤传值⽅式编译器直接报错,因为语法逻辑上会引发⽆穷递归调⽤。 拷⻉构造函数也可以多个参数,但是第⼀个参数必须是类类型对象的引⽤,后⾯的参数必须有缺省值。
// 编译报错:error C2652: “Date”: ⾮法的复制构造函数: 第⼀个参数不应是“Date”
//Date(Date d);
Date(const Date& d)
{
	_year = d._year;
	_month = d._month;
	_day = d._day;
}

2.1 错误演示: 编译报错:error C2652: “Date”: ⾮法的复制构造函数: 第⼀个参数不应是“Date”。
在这里插入图片描述

  1. C++规定自定义类型对象进行拷贝⾏为必须调⽤拷⻉构造,所以这⾥自定义类型传值传参和传值返回都会调用拷贝构造完成。
  2. 若未显式定义拷贝构造,编译器会⽣成⾃动⽣成拷贝构造函数。⾃动⽣成的拷贝构造对内置类型成员变量会完成值拷贝/浅拷贝⼀个字节⼀个字节的拷贝),对⾃定义类型成员变量会调用他的拷贝构造。
    c++规定:类类型传值传参必须调用拷贝构造。
  3. 像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器⾃动⽣成的拷⻉构造就可以完
    成需要的拷贝,所以不需要我们显⽰实现拷贝构造。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器⾃动⽣成的拷⻉构造完成的值拷⻉/浅拷⻉不符合我们的需求,所以需要我们⾃⼰实现深拷贝(对指向的资源也进⾏拷贝)。像MyQueue这样的类型内部主要是⾃定义类型Stack成员,编译器⾃动⽣成的拷贝构造会调⽤Stack的拷贝构造,也不需要我们显示实现
    MyQueue的拷贝构造。这⾥还有⼀个⼩技巧,如果⼀个类显⽰实现了析构并释放资源,那么他就
    需要显⽰写拷⻉构造,否则就不需要。
  4. 传值返回会产生⼀个临时对象调⽤拷贝构造,传值引用返回,返回的是返回对象的别名(引用),没有产生拷贝。但是如果返回对象是⼀个当前函数局部域的局部对象,函数结束就销毁了,那么使⽤引⽤返回是有问题的,这时的引⽤相当于⼀个野引用,类似⼀个野指针⼀样。传引用返回可以减少拷⻉,但是⼀定要确保返回对象,在当前函数结束后还在,才能⽤引⽤返回。
    无限递归
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class Date {
public:
	Date(int year = 11, int month = 1, int day = 30) {
		_year = year;
		_month = month;
		_day = day;
	}
	// 编译报错:error C2652: “Date”: ⾮法的复制构造函数: 第⼀个参数不应是“Date”
	//Date(Date d);
	Date(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	Date(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(2024, 7, 5);
	tmp.print();
	return tmp;
}

int main()
{
	Date d1(2024, 9, 21);
	// C++规定⾃定义类型对象进⾏拷⻉⾏为必须调⽤拷⻉构造,所以这⾥传值传参要调⽤拷⻉构造
		// 所以这⾥的d1传值传参给d要调⽤拷⻉构造完成拷⻉,传引⽤传参可以较少这⾥的拷⻉
	Func1(d1);
	cout << &d1 << endl;
	//这里可以完成拷贝,但是不是拷贝构造,只是一个普通构造
	Date d2(&d1);
	d1.print();
	d2.print();
	//这样写排才是拷贝构造,通过同类型的对象初始化对象,而不是指针
	Date d3(d1);
	d2.print();
	//也可以这样写,这里也是拷贝构造
	Date d4 = d1;
	d2.print();
	//Func2返回了一个局部对象tmp的引用作为返回值
	// Fun2函数结束,tmp对象就销毁了,相当于了一个野引用
	Date ret = Func2();
	ret.print();
	return 0;
}

结果

stack

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
typedef int  STDataType;
class Stack
{
public:
	Stack(int n = 4)
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (_a == NULL)
		{
			perror("malloc fail!");
			return;
		}
		_capacity = n;
		_top = 0;
	}
	Stack(const Stack& st)
	{
		//需要对_a指向资源创建同样大的资源再拷贝
		_a = (STDataType*)malloc(sizeof(STDataType) * st._capacity);
		if (_a == NULL)
		{
			perror("malloc fail!");
			return;
		}
		memcpy(_a,st._a, sizeof(STDataType) * st._top);
		_top = st._top;
		_capacity = st._capacity;

	}
	void Push(STDataType x)
	{
		if (_top == _capacity)
		{
			int newcapacity = _capacity * 2;
			STDataType* tmp = (STDataType*)realloc(_a, newcapacity *
				sizeof(STDataType));
			if (tmp == NULL)
			{
				perror("realloc fail");
				return;
			}
			_a = tmp;
			_capacity = newcapacity;
		}
		_a[_top++] = x;
	}
	~Stack()
	{
		cout << "~Stack()" << endl;
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}
private:
	STDataType* _a;
	size_t _capacity;
	size_t _top;
};
// 两个Stack实现队列
class MyQueue
{
public:
private:
	Stack pushst;
	Stack popst;
};
int main()
{
	Stack st1;
	st1.Push(1);
	st1.Push(2);
	// Stack不显⽰实现拷⻉构造,⽤⾃动⽣成的拷⻉构造完成浅拷⻉
	// 会导致st1和st2⾥⾯的_a指针指向同⼀块资源,析构时会析构两次,程序崩溃
	Stack st2 = st1;
	MyQueue mq1;
	// MyQueue⾃动⽣成的拷⻉构造,会⾃动调⽤Stack拷⻉构造完成pushst/popst
	// 的拷⻉,只要Stack拷⻉构造⾃⼰实现了深拷⻉,他就没问题
	MyQueue mq2 = mq1;
	return 0;
}

5. 赋值运算符重载

5.1 运算符重载

(1)当运算符被用于类类型的对象时,C++语⾔允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象使用运算符时,必须转换成调用对应运算符重载,若没有对应的运算符重载,则会编译报错。
在这里插入图片描述

(2)运算符重载是具有特殊名字的函数,他的名字是由operator和后⾯要定义的运算符共同构成。和其他函数⼀样,它也具有其返回类型和参数列表以及函数体。
(3) 重载运算符函数的参数个数和该运算符作用的运算对象数量⼀样多。⼀元运算符有⼀个参数,⼆元运算符有两个参数,⼆元运算符的左侧运算对象传给第⼀个参数,右侧运算对象传给第⼆个参数。
(4)如果⼀个重载运算符函数是成员函数,则它的第⼀个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数⽐运算对象少⼀个。
(5) 运算符重载以后,其优先级和结合性与对应的内置类型运算符保持⼀致。
(6)不能通过连接语法中没有的符号来创建新的操作符:⽐如operator@。
(7) . * :: sizeof ?: . 注意以上5个运算符不能重载。(选择题里面常考,⼤家要记⼀下)
(8)重载操作符⾄少有⼀个类类型参数,不能通过运算符重载改变内置类型对象的含义,如: intoperator+(int x, int y)
(9) ⼀个类需要重载哪些运算符,是看哪些运算符重载后有意义,比如Date类重载operator-就有意
义,但是重载operator+就没有意义。
(10)重载++运算符时,有前置++和后置++,运算符重载函数名都是operator++,⽆法很好的区分。C++规定,后置++重载时,增加⼀个int形参,跟前置++构成函数重载,方便区分。

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;
	}
	bool operator ==(const Date& d)
	{
		return _year == d._year
			&& _month == d._month
			&& _day == d._day;
	}
	Date& operator++()
	{
		cout << "前置++" << endl;
		//....
		return *this;
	}
	Date operator++(int)
	{
		Date tmp;
		cout << "后置++" << endl;
		//....
		return tmp;
	}
	//private:
	int _year;
	int _month;
	int _day;
};


int main()
{
	Date d1(2024, 9, 22);
	Date d2(2024, 9, 221);
	//运算符重载函数可以显示调用
	d1.operator==( d2);
	//编译器会转换成 d1.operator == (d2);
	d1 == d2;
	//编译器会转换成 d1.operator++();
	++d1;//前置加加
	//编译器会转换成 d1.operator++(0);
	d1++;//后置加加

	return 0;
}

在这里插入图片描述

(11)重载<<和>>时,需要重载为全局函数,因为重载为成员函数,this指针默认抢占了第⼀个形参位置,第⼀个形参位置是左侧运算对象,调用时就变成了 对象<<cout,不符合使用习惯和可读性。
重载为全局函数把ostream/istream放到第⼀个形参位置就可以了,第⼆个形参位置当类类型对
象。
代码1:

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
//编译报错:“operator+”必须至少有一个类类型的形参
int operator+(int x, int y)
{
	return x - y;
}
class A
{
public:
	void func()
	{
		cout << "A::func()" << endl;
	}
};
typedef void(A::* PF)();//成员函数指针类型

int main()
{
	//c++规定成员函数要加&才能取到函数指针
	PF pf = &A::func;
	A obj;//定义ob类对象temp
	// 对象调用成员函数指针时,使用.*运算符
	(obj.*pf)();

	return 0;
}

代码2:

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提供getxx函数
//3.友元函数
//4.重载为成员变量
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(2024,9,22);
	Date d2(2024,9,22);
	//运算符重载函数可以显示调用
	operator==(d1, d2);
	//编译器会转换成 operator == (d1,d2);
	d1 == d2;

	return 0;
}

5.2 赋值运算符重载

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

  1. 赋值运算符重载是⼀个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成
    const 当前类类型引⽤,否则会传值传参会有拷贝
  2. 有返回值,且建议写成当前类类型引⽤,引⽤返回可以提⾼效率,有返回值⽬的是为了⽀持连续赋值场景。
  3. 没有显式实现时,编译器会⾃动⽣成⼀个默认赋值运算符重载,默认赋值运算符重载⾏为跟默认拷⻉构造函数类似,对内置类型成员变量会完成值拷贝/浅拷贝(⼀个字节⼀个字节的拷贝),对⾃定义类型成员变量会调⽤他的赋值重载函数。“stack需要自己实现深拷贝的operator=”
  4. Date这样的类成员变量全是内置类型且没有指向什么资源,编译器⾃动⽣成的赋值运算符重载就可以完成需要的拷贝,所以不需要我们显示实现赋值运算符重载。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器⾃动⽣成的赋值运算符重载完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进⾏拷贝)。像MyQueue这样的类型内部主要是⾃定义类型Stack成员,编译器⾃动⽣成的赋值运算符重载会调⽤Stack的赋值运算符重载,也不需要我们显示实现MyQueue的赋值运算符重载。这⾥还有⼀个⼩技巧,如果⼀个类显示实现了析构并释放资源,那么他就需要显示写赋值运算符重载,否则就不需要。
    结论:
    1.构造一般需要自己写,自己传参定义初始化。
    2.析构,构造时有申请(如malloc或fopen)等,就需要显示写析构。
    3,拷贝构造和赋值构造,显示写了析构
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	Date(const Date& d)
	{
		cout << "Date(const Date & d)" << endl;
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	//传引用返回减少拷贝
	// d1 = d2;

	Date &operator =(const Date& d)
	{
		//不要检查自己给自己赋值的情况
		if(this != &d)
		{
			_year == d._year;
			_month == d._month;
			_day == d._day;
		}
		//d1 = d2 表达式的返回对象应该是d1,也就是*this
		return *this;
	}
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
	private:
	int _year;
	int _month;
	int _day;
};



int main()
{
	Date d1(2024, 9, 22);
	Date d2(d1);
	Date d3(2024, 10, 2);
	d1 = d3;
	//需要注意这里是拷贝构造,不是赋值重载
	//请牢牢记住赋值重载完成两个已经存在的对象直接的拷贝赋值
	// 而拷贝构造用于一个对象拷贝初始化给另一个要创建的对象
	Date   d4 = d1;
	return 0;
}

部分运行结果:
在这里插入图片描述

5.3 日期类实现

源代码

Date.h
#pragma once
#include<iostream>
using namespace std;
#include<assert.h>
class Date {
	//友元函数声明
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);
public:
	Date(int year = 1900, int month = 1, int day = 1);
	void Print()const;
	// 直接定义类里面,他默认是inline
	// 频繁调用
	int GetMonthDay(int year, int month)
	{
		assert(month > 0 && month < 13);
		static int monthDayArray[13] = { -1,31,28,31,30,31,30,31,31,30,31,30,31 };
		// 365天 5h 四年会多出1天
		if (month == 2 && (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
		{
			return 29;
		}
		else
		{
			return monthDayArray[month];
		}
	}
	bool CheckDate();
	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;
	//d1 += 天数
	Date& operator+=(int day);
	Date operator+(int day) const;
	//d1 -= 天数
	Date& operator-=(int day);
	Date operator-(int day) const;
	//d1 -d2
	int operator-(const Date& d) const;

	// ++d1 -> d1.perator++()
	Date& operator++();
	//d1++ ->d1.opterator++(0)
	//为了区分,构成重载,给后置++,强行增加了一个int形参
	//这里不需要写形参名,因为接收值是多少不重要,也不需要用
	//这个参数仅仅是为了跟前置++构成重载区分
	Date operator++(int);
	Date& operator--();
	Date  operator--(int);
	//流插入
	//不建议,因为Date*this占据一个参数位置,使用d<<cout不符合习惯
	//void operator <<(ostream&out);

 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"
bool Date::CheckDate()
{
	if (_month < 1 || _month>12
		||_day<1||_day>GetMonthDay(_year,_month)
		)
	{
		return false;
	}
	else
	{
		return true;
	}
}
Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;
	if (!CheckDate())
	{
		cout << "日期不正确" << endl;
	}
}
void Date::Print()const
{
	cout << _year << "/" << _month <<"/" << _day << endl;
}
//d1<d2
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;
}
//d1<=d2
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);
}
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);
}
//d1+= 50
//d1 += -50

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;
}
Date Date::operator+(int day)const
{
	Date tmp = *this;
	tmp += day;
	return tmp;
}
//d1 -= 100
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;
}

//++d1
Date& Date::operator++()
{
	*this += 1;
	return *this;
}
//d1++
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 flag * n;

}
ostream& operator<<(ostream& out, const Date& d)
{
	out << d._year << "年" << d._month << "月" << d._day << "月" << endl;
	return out;
}
istream& operator>>(istream& in, Date& d)
{
	cout << "请依次输入年月日:>";
	in >> d._year >> d._month >> d._day;
	if (!d.CheckDate())
	{
		cout << "日期非法" << endl;
	}
	return in;
}


test.cpp
#define _CRT_SECURE_NO_WARNINGS 1
# include"Date.h"
void TestDate1()
{
	//测试加减
	Date d1(2024, 9, 28);
	Date d2 = d1 + 3000;
	d1.Print();
	d2.Print();
	Date d3(2024, 9, 28);
	Date d4 = d3 - 4000;
	d3.Print();
	d4.Print();
	Date d5(2024, 9, 28);
	d5 += -5000;
	d5.Print();
}
void TestDate2()
{
	Date d1(2024, 9, 28);
	Date d2 = ++d1;
	d1.Print();
	d2.Print();
	Date d3 = d1++;
	d1.Print();
	d3.Print();
	/*d1.operator++(1);
	d1.operator++(100);
	d1.operator++(0);
	d1.Print();*/
}
void TestDate3()
{
	Date d1(2024, 4, 14);
	Date d2(2023, 4, 14);
	int n = d1 - d2;
	cout << n << endl;
	n = d2 - d1;

}
void TestDate4()
{
	Date d1(2024, 9, 28);
	Date d2 = d1 + 300000;
	//operator<<(cout,d1);
	cout << d1;
	cout << d2;
	cin>> d1 >> d2;
	cout << d1 << d2;


}
void TestDate5()
{
	Date d1(2024, 9, 28);
	d1.Print();
	//d1 += 200;
	d1 + 100;
	Date d2(2024, 10, 28);
	d2.Print();

	d2 += 100;
	d1 < d2;
	d2 < d1;


}

int main()
{
	//TestDate1();
	//TestDate2();
	//TestDate3();
	//TestDate4();
	TestDate5();
	return 0;
}

6. 取地址运算符重载

6.1 const成员函数

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

class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	//void Print(const Date *const this) const
	void Print() const
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
//private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	//这里非const 对象也可以调用const成员函数是一种权限缩小
	Date d1(2024,9,22);
	d1.Print();
	const Date d2(2024, 9, 21);
	d2.Print();

	return 0;
}

在这里插入图片描述

6.2 取地址运算符重载

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

class Date
 {
 public :
 Date* operator&()
{
 return this;
 // return nullptr; }

 const Date* operator&()const
 {
 return this;
 // return nullptr;
 }
 private :
 int _year ; // 年
 int _month ; // ⽉
int _day ; // ⽇

总结

以上就是类和对象(中)的全部内容了,内容实在太多总结了好多天才完成,希望大家可以认真多次观看,看完收获一定会很多。喜欢的可以一键三连支持博主!!!


http://www.kler.cn/news/324754.html

相关文章:

  • ELK-05-skywalking监控SpringCloud服务日志
  • Java 图片合成
  • 【CKA】二、节点管理-设置节点不可用
  • UDP与TCP那个传输更快
  • 【高阶数据结构】平衡二叉树(AVL)的插入(4种旋转方法+精美图解+完整代码)
  • 深度解析:Debian 与 Ubuntu 常用命令的区别与联系
  • Electron 安装以及搭建一个工程
  • GGHead:基于3D高斯的快速可泛化3D数字人生成技术
  • TCN预测 | MATLAB实现TCN时间卷积神经网络多输入单输出回归预测
  • WPF入门教学十三 MVVM模式简介
  • 极狐GitLab 17.4 重点功能解读【二】
  • Git 工作区、暂存区和版本库
  • 从事人工智能学习Python还是学习C++?
  • 巴鲁夫rfid读头国产平替版——高频RFID读写器
  • element的描述列表<el-descriptions>添加字典翻译功能
  • Lodash库
  • 24年Novartis诺华制药社招入职SHL测评:综合能力、性格问卷、动机问卷高分攻略
  • count(1),count(*)与 count(‘列名‘) 的区别
  • Docker部署MongoDB教程
  • 3. 轴指令(omron 机器自动化控制器)——>MC_MoveZeroPosition
  • Linux内核启动之根文件系统挂载
  • 串、数组和广义表
  • 一键式商品信息获取:京东API返回值深度挖掘
  • iOS 使用使用渐变色生成图片
  • 第九届蓝桥杯嵌入式省赛程序设计题解析(基于HAL库)
  • 可视化服务编排:jvs-logic API出参加密实战教程
  • 基于springboot vue 大学生竞赛管理系统设计与实现
  • LoRA - 大模型的低秩适应方法
  • springboot第74集:设计模式
  • 在二维平面中,利用时差定位(TDOA)技术,结合N个锚点,通过三边法进行精确定位,采用MATLAB实现