类和对象三部曲(two)

拼搏百天,C嘎嘎直接手拿把掐

4281b415a8f343bea9d211fbb66da0a8.jpeg

青春期猪头AD钙不会梦到狸花猫学姐 

6个默认成员函数

如果一个类中什么成员都没有,简称为空类。 空类中真的什么都没有吗?

并不是,任何类在什么都不写时,编译器会自动生成以下6个默认成员函数。

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

2bdac8f5439548db920df1e554e45097.png

初始化函数:

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

这函数有什么问题么?

最大的问题:容易忘记(这难道不是我的问题吗)

C嘎嘎祖师爷显然也发现了这个问题,于是,就搞了个东西出来:构造函数

构造函数

构造函数听起来是不是很朦胧?

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

其实构造函数不是创建对象,而是初始化,特征如下:

1. 函数名与类名相同

2. 无返回值(不是void,是啥都妹有)

3. 对象实例化时编译器自动调用对应的构造函数

4. 构造函数可以重载

哦豁,支持重载: 

9b586ed2ba1d4121a95e1e1cfaa700ec.png

举个例子:

#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;
	}
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1;
	d1.Print();

	Date d2(2024, 3, 25);
	d2.Print();
	return 0;
}

 6162225ebf014c3f90ae4f38cc8df428.png

对象实例化的时候自动调用+支持重载(是不是很神奇) 

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

如果出现错误,肯定不是因为重载,而是对重载的指定不明确

那这两种写法能不能合并呢?

当然,用全缺省香的很:

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

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

请看下面这段代码:

class f1
{
public:
		void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	f1 f;
	f.Print();
	return 0;
}

都说默认生成构造函数嘛,那是不是意味着可以直接初始化了呢?

可是结果:诶?怎么会是呢?

 08ca07ac49a047789e92dd1532069f1b.png

初始化了个寂寞,这默认的构造函数要它何用

先来看概念:

C++把类型分成内置类型(基本类型)和自定义类型

内置类型是语言提供的数据类型:int ,char,double...

自定义类型是我们自己定义的类型:struct ,class ,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 time;
};
int main()
{
	date f;
	f.Print();
	return 0;
}

 但是这样显然有点奇怪,所以在C++11中针对内置类型成员不初始化的缺陷,打了个补丁:

内置类型成员变量在类中声明时可以给默认值

class Time
{
public:
	Time()
	{
		cout << "Time()" << endl;
		_hour = 0;
		_minute = 0;
		_second = 0;
	}
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;
}

总结一下就是:分析一个类型成员和初始化需求

需要写构造函数就自己写,不需要就用编译器自己生成的

绝大多数场景都需要自己写构造函数,且只有没写的时候才生成默认构造函数,但凡写了都不会再生成

无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。

tips:无参构造函数、全缺省构造函数、编译器默认生成构造函数,都可以认为是默认构造函数

一般情况下建议全缺省

析构函数

析构函数是什么?

如果说构造函数是初始化,那析构函数就是完成对象中资源的清理(不是销毁、不是销毁、不是销毁!)

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

析构函数是特殊的成员函数,有这样的特征:

1. 析构函数名是在类名前加上字符 ~(很好理解,这是按位取反,构造函数的反)

2. 无参数无返回值类型

3. 一个类只能有一个析构函数,若未显式定义,系统会自动生成默认的析构函数

tips:析构函数不能重载(毕竟无参数无返回值类型)

4. 对象生命周期结束时,C++编译系统系统自动调用析构函数

 那析构函数设计的意义在于?

很好,是因为要防止忘(忘记释放空间会造成内存泄漏,由编译器自动调用就好很多)

对于编译器自动生成的析构函数,会不会做一些事情呢?

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

结果:程序运行结束后输出:~Time()

解释:在main方法中没有直接创建Time类的对象,但是最后调用了Time类的析构函数(main方法中创建了Date对象d,d包含四个成员变量,_year,_month,_day是内置类型成员,_t是Time类对象),内置类型成员销毁时不需要资源清理,最后系统直接将其内存回收掉即可,d销毁时,_t类对象也要被销毁,要调用Time类的析构函数,但是main函数不能够直接调用Time类的析构函数,实际释放的时候释放的是Date类对象,所以编译器会调用Date类的析构函数,Date没有显示提供,所以编译器默认生成一个析构函数(目的是在其内部调用Time类的析构函数),当Date对象销毁时,要保证内部每个自定义对象都可以正确销毁

main函数中并没有直接调用Time类析构函数,而是显式调用编译器为Date类生成的默认析构函数

tips:创建哪个类的对象则调用该类的构造函数,销毁哪个类的对象则调用该类的析构函数

如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数(比如 Date类);有资源申请时,一定要写,否则会造成内存泄漏(比如Stack类)

先定义的先构造,后定义的先析构(毕竟在栈帧,要符合规律)

默认析构做什么?
同构造函数类似,内置类型不做处理,自定义类型去调用他的析构

自定义类型的尽头是内置类型

请看下面的代码演示:

class Date
{
public:
	int _year;
	Date(int year)
	{
		_year = year;
	}
	~Date()
	{
		cout << "~Date" << _year << endl;
	}
};
int main()
{
	Date d1(1);
	Date d2(2);
	Date d3(3);
	Date d4(4);
	return 0;
}

0b7caca61bef4e5f8bf876fd01f884cd.png

这是局部的析构,那全局或者静态的是怎么样的?

class Date
{
public:
	int _year;
	Date(int year)
	{
		_year = year;
	}
	~Date()
	{
		cout << "~Date" << _year << endl;
	}
};
int main()
{
	Date d1(1);
	Date d2(2);
	Date d3(3);
	static Date d4(4);
	return 0;
}

75c0df9b9bf045469bd1b3c8a823f242.png

没错,由于静态/全局的生命周期是整个程序运行结束才结束,所以他们的析构肯定都发生在局部变量析构完之后 

那么这样呢?

class Date
{
public:
	int _year;
	Date(int year)
	{
		_year = year;
	}
	~Date()
	{
		cout << "~Date" << _year << endl;
	}
};
static Date d5(5);
Date d6(6);
int main()
{
	Date d1(1);
	Date d2(2);
	Date d3(3);
	static Date d4(4);
	return 0;
}

c6e5345a317d4896b4528e850a2e3155.jpeg

5bdf8391514f4535b459f582b098901f.png

 答对没?总结一下就是:

先局部,后静态全局,后进先出

拷贝构造函数

拷贝构造函数是什么?

看个梗图:

988918a9ce5d42589ed87a3817dd7297.png

程序员小孩:CV工程师
那在创建对象时,可否创建一个与已存在对象一某一样的新对象呢? 拷贝构造函数:只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时由编译器自动调用。

拷贝构造格式:

class Date
{
public:
	int _year;
	int _month;
	int _day;
	Date(Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
};
Date d1(2024,1,28);
Date d2(d1);

C++规定自定义的类型都会调用拷贝构造,传引用就不用啦:

class Date
{
public:
	int _year;
	int _month;
	int _day;
	Date(int year=1,int month=1,int day=1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	Date(Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	~Date()
	{
		cout << "~Date" << _year << endl;
	}
};
void func1(Date d)
{

}
void func2(Date& d)
{

}
int main()
{
	Date d1(2024, 4, 27);
	func1(d1);
	func2(d1);
	return 0;
}

 拷贝构造是一个特殊的构造,也是自动调用的(调用拷贝构造,要先传参,这里的传值传参会形成新的拷贝构造)

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

传值传参无法破局,引用以身入局胜天半子

但是呢,为了避免某些昏头崽赔了夫人又折兵,

Date d1(2024,4,29)

Date d2(d1)

class Date
{
public:
	Date(int year=1,int month=1,int day=1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	Date(Date& d)
	{
		d._year = _year;
		d._month = _month;
		d._day = _day;
	}
	~Date()
	{
		cout << "~Date" << _year << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

一般这样写:

class Date
{
public:
	Date(int year=1,int month=1,int day=1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	Date(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	~Date()
	{
		cout << "~Date" << _year << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

加const可以很好地保护这个对象 

这里是一种权限的缩小,从可读可写变成只读(融汇贯通是这样的)

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

be9937cdd3874de2b281cdda72616468.png

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

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

#include<iostream>
using namespace std;

class Time
{
public:
	Time()
	{
		_hour = 1;
		_minute = 1;
		_second = 1; 
	}
	Time(const Time& t)
	{
		_hour = t._hour;
		_minute = t._minute;
		_second = t._second;
		cout << "Time::Time(const 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 d1;
	// 用已经存在的d1拷贝构造d2,此处会调用Date类的拷贝构造函数
	// 但Date类并没有显式定义拷贝构造函数,则编译器会给Date类生成一个默认的拷贝构造函数
	Date d2(d1);
	return 0;
}

tips:这个Time构造函数是必须写的,因为是自定义类型,必须要写拷贝构造,拷贝构造也是构造函数,构造函数是在没有构造函数的情况下编译器会自动生成一份,但是现在已经有了

我们还可以这样强制让编译器生成一份构造函数:

Time() = default;

啊上面栗子有点复杂,看这个:

 啊不是

是这个:

#include<iostream>
using namespace std;

class Time
{
public:
	Time()
	{
		_hour = 1;
		_minute = 1;
		_second = 1; 
	}
	Time(const Time& t)
	{
		_hour = t._hour;
		_minute = t._minute;
		_second = t._second;
	}
	void Print(Time T)
	{
		cout << T._hour << endl;
		cout << T._minute << endl;
		cout << T._second << endl;
	}
private:
	int _hour;
	int _minute;
	int _second;
};

int main()
{
	Time t1;
	Time t2(t1);
	t1.Print(t1);
	t2.Print(t2);

	return 0;
}

把拷贝函数注释掉会发现是一样的:

#include<iostream>
using namespace std;

class Time
{
public:
	Time()
	{
		_hour = 1;
		_minute = 1;
		_second = 1; 
	}
	/*Time(const Time& t)
	{
		_hour = t._hour;
		_minute = t._minute;
		_second = t._second;
	}*/
	void Print(Time T)
	{
		cout << T._hour << endl;
		cout << T._minute << endl;
		cout << T._second << endl;
	}
private:
	int _hour;
	int _minute;
	int _second;
};

int main()
{
	Time t1;
	Time t2(t1);
	t1.Print(t1);
	t2.Print(t2);

	return 0;
}

拷贝对内置类型也做了处理 (就上面说的浅拷贝)

自定义类型成员调用它的拷贝构造

有的时候自定义生成的拷贝构造靠不住,需要靠自己:如果指针指向同一块空间,那有一个就会成为野指针(释放空间不能释放两次,因为有可能释放后的空间被快速应用于其它地方)

#include<iostream>
using namespace std;

typedef int DataType;
class Stack
{
public:
	Stack(size_t capacity = 10)
	{
		_array = (DataType*)malloc(capacity * sizeof(DataType));
		if (nullptr == _array)
		{
			perror("malloc申请空间失败");
			return;
		}_size = 0;
		_capacity = capacity;
	}
	void Push(const DataType& data)
	{
		// CheckCapacity();
		_array[_size] = data;
		_size++;
	}
	~Stack()
	{
		if (_array)
		{
			free(_array);
			_array = nullptr;
			_capacity = 0;
			_size = 0;
		}
	}
private:
	DataType* _array;
	size_t _size;
	size_t _capacity;
};
int main()
{
	Stack s1;
	s1.Push(1);
	s1.Push(2);
	s1.Push(3);
	s1.Push(4);
	Stack s2(s1);
	return 0;
}

浅拷贝对于动态内存开辟的基本上都不适用

这样的类型适用于深拷贝,人生极速版(不要生烤贝)

深拷贝这样搞:

Stack(const Stack& s)
{
	DataType* tmp = (DataType*)malloc(s._capacity * (sizeof(DataType)));
	if (tmp == nullptr)
	{
		perror("malloc fail");
		exit(-1);
	}

	memcpy(tmp, s._array, sizeof(DataType) * s._size);

	_array = tmp;
	_size = s._size;
	_capacity = s._capacity;
}

临时变量具有常性,是不能被修改的

4e4c7cc9a19c47e3bade1bb48fd3d43e.png

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

赋值运算符重载

自定义类型不能比较大小,准确的是说编译器不知道它怎么比,所以比不了,所以可以自己搓一个比较函数:

#include<iostream>
using namespace std;

class Time
{
public:
	Time(int hour,int minute,int second)
	{
		_hour = hour;
		_minute = minute;
		_second = second;
	}
	Time(const Time& t)
	{
		_hour = t._hour;
		_minute = t._minute;
		_second = t._second;
	}
	void Print(Time T)
	{
		cout << T._hour << endl;
		cout << T._minute << endl;
		cout << T._second << endl;
	}
	int _hour;
	int _minute;
	int _second;
};

bool Dataless(const Time& x, const Time& y)
{
	if (x._hour < x._hour)
	{
		return true;
	}
	else if (x._hour == x._hour)
	{
		if (x._minute < y._minute)
		{
			return true;
		}
		else if (x._minute == y._minute)
		{
			return x._second < y._second;
		}
		else if (x._minute == y._minute)
		{
			return x._second < y._second;
		}
	}
	return false;
}

但是这样比较依赖于写代码人的素质,需要很高端的(如上)的命名才比较方便 

祖师爷不能容忍这个,受不了一点

新规可以形成好规范,即运算符重载(对运算符的行为重新定义、重新控制)

bool operator<(const Time& x, const Time& y)
{
	if (x._hour < x._hour)
	{
		return true;
	}
	else if (x._hour == x._hour)
	{
		if (x._minute < y._minute)
		{
			return true;
		}
		else if (x._minute == y._minute)
		{
			return x._second < y._second;
		}
		else if (x._minute == y._minute)
		{
			return x._second < y._second;
		}
	}
	return false;
}

可读性会强很多

但是祖师爷不止于此,他终极目标是自定义类型也可以用 

#include<iostream>
using namespace std;

class Time
{
public:
	Time(int hour,int minute,int second)
	{
		_hour = hour;
		_minute = minute;
		_second = second;
	}
	Time(const Time& t)
	{
		_hour = t._hour;
		_minute = t._minute;
		_second = t._second;
	}
	void Print(Time T)
	{
		cout << T._hour << endl;
		cout << T._minute << endl;
		cout << T._second << endl;
	}
	int _hour;
	int _minute;
	int _second;
};

bool operator<(const Time& x, const Time& y)
{
	if (x._hour < x._hour)
	{
		return true;
	}
	else if (x._hour == x._hour)
	{
		if (x._minute < y._minute)
		{
			return true;
		}
		else if (x._minute == y._minute)
		{
			return x._second < y._second;
		}
		else if (x._minute == y._minute)
		{
			return x._second < y._second;
		}
	}
	return false;
}

int main()
{
	Time t1(0, 4, 9);
	Time t2(5, 2, 0);
	t1.Print(t1);
	t2.Print(t2);
	cout << (t1 < t2) << endl;   //    <<运算符优先级比较高,需要加括号
	return 0;
}

可以直接打印是因为有this指针默认自己找

有的运算符没必要重载,参数默认从左到右,因为有的运算符可能是 - ,不能变顺序

然后这是在类外面访问成员变量,一般来说成员变量都是私有的,可以这样解决:

int GetHour()
{
	return _hour;
}

Java喜欢像上面那样写个函数 

还可以在类里面写运算符重载,类里面访问嘎嘎香,但是又有个问题,会显示参数过多,因为成员函数有默认的this指针,而运算符重载函数要求有几个操作数就要有相应的数量的参数(悄咪咪的已经传了个值)

所以在比较的时候得这么比:

cout << d1.operator == (d2) << endl; 

也可以显式调用 

拜拜拜拜我先吃饭去 

回来咯,但第二天

运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似

函数名:关键字operator后面接需要重载的运算符符号

函数原型:返回值类型 operator操作符(参数列表)

tips:

不能通过连接其他符号来创建新的操作符:比如operator@

重载操作符必须有一个类类型参数(不能重载运算符改变内置类型行为)

用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不能改变其含义

作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐 藏的this

.*我是.*不是*      ::      sizeof      ?:我是三目运算符     .          这5个运算符不能重载(笔试选择题)

 .*是什么?

是通过对象调用成员函数的指针(一般不这么玩吧?):

#include<iostream>
using namespace std;

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

typedef void(ob::* pobfunc)();

int main()
{
	pobfunc p = &ob::func;
	ob tmp;
	(tmp.*p)();
	return 0;
}

函数指针一般这样调用:

(*p)();

 像上面那样调用的核心目的是为了传递this指针

 还有一种可以额外说一哈:赋值运算符重载(拷贝构造,拷贝构造是构造,需要调用初始化,用同类型对象进行初始化),但赋值运算符重载可以让两个已经存在的对象进行拷贝赋值

这样搞:

#include<iostream>
using namespace std;

class Date
{
public:
	void operator=(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}

private:
	int _year;
	int _month;
	int _day;

};

 为了支持连续的赋值,要有返回值的:

#include<iostream>
using namespace std;

class Date
{
public:
	Date operator=(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
		return *this;
	}

private:
	int _year;
	int _month;
	int _day;

};

 但是很浪费,因为是传值,所以返回的是它的拷贝构造,就又要调用一遍拷贝构造太浪费了,所以这样改就好了:

#include<iostream>
using namespace std;

class Date
{
public:
	Date& operator=(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
		return *this;
	}

private:
	int _year;
	int _month;
	int _day;

};

为了避免自己给自己赋值(谁会这么闲),一般这样干:

#include<iostream>
using namespace std;

class Date
{
public:
	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;

};

编译器会默认生成一份赋值重载(浅拷贝),但我们还是需要写的(对于栈这种开空间的)

 赋值重载不能重载成全局的,因为:

// 全局的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;
}
void Test()
{
	Date d1(2018, 9, 26);
	Date d2(2018, 9, 27);
	cout << (d1 == d2) << endl;
}

赋值运算符重载格式:

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

返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值

检测是否自己给自己赋值

返回*this :要复合连续赋值的含义

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

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	int _year;
	int _month;
	int _day;
};
// 赋值运算符重载成全局函数,注意重载成全局函数时没有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 =”必须是非静态成员

VS贴心的直接提示了:

 前置++和后置++重载

来看看++这个怎么重载吧:

#include<iostream>
using namespace std;

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	// 前置++:返回+1之后的结果
	// 注意:this指向的对象函数结束后不会销毁,故以引用方式返回提高效率
	Date& operator++()
	{
		_day += 1;
		return *this;
	}
	// 后置++:
	// 前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载
	// C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递
	// 注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存一份,然后给this + 1
	//而temp是临时对象,因此只能以值的方式返回,不能返回引用
	Date operator++(int)
	{
		Date temp = (*this);
		_day += 1;
		return temp;
	}
private:
	int _year;
	int _month;
	int _day;
}; 
int main()
{
	Date d;
	Date d1(2022, 1, 13);
	d = d1++;
	d = ++d1; 
	return 0;
}

 就这样,然后田中宝宝:

 

const成员函数

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

成员函数如果是一个对成员变量只进行读访问的函数,则建议加const

若要进行写访问,则不能加const 

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

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

这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需
要重载,比如想让别人获取到指定的内容 

reserve sky

倒反天罡

#include<iostream>
using namespace std;

class Date
{
public:
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	//作为成员函数重载,this指针占据第一个参数,Date必须是左操作数
	void operator<<(ostream& out)
	{
		out << _year << "年" << _month << "月" << _day << "日" << endl;
	}

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

int main()
{
	Date d1(1949, 12, 1);
	d1.operator<<(cout);
	d1 << cout;
	return 0;
}

还能这么玩?这不reserve sky了有点 

所以它写不成成员函数,要写成全局函数,但是又会存在一个成员变量私有在外面访问不了的情况,所以可以加个友元声明,让类外面的函数可以访问类里面的变量:

#include<iostream>
using namespace std;

class Date
{
public:
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	friend void operator<<(ostream& out, const Date& d);
private:
	int _year;
	int _month;
	int _day;
};


void operator<<(ostream& out,const Date& d)
{
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
}


int main()
{
	Date d1(1949, 12, 1);
	operator<<(cout, d1);
	cout << d1;
	return 0;
}

这样就支持连续输出了:

#include<iostream>
using namespace std;

class Date
{
public:
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	friend ostream& operator<<(ostream& out, const Date& d);
private:
	int _year;
	int _month;
	int _day;
};


ostream& operator<<(ostream& out,const Date& d)
{
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
	return out;
}


int main()
{
	Date d1(1949, 12, 1);
	operator<<(cout, d1);
	cout << d1 << d1;
	return 0;
}

干脆把插入也写了:

#include<iostream>
using namespace std;

class Date
{
public:
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);
private:
	int _year;
	int _month;
	int _day;
};


ostream& operator<<(ostream& out,const 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;
}

int main()
{
	Date d1(1949, 12, 1);
	cin >> d1;
	operator<<(cout, d1);
	cout << d1 << d1;
	return 0;
}

 下面程序还有个缺陷,就是在+的时候添加一个检查,检查加完之后的结果是否合法

 完整实现日期类

上面学过很多了,过来写代码

我们计算日期的相关操作需要频繁的知道某年某月有几天,所以在类里封装一个内联函数:

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

class Date
{
public:
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	//获取某年某月天数
	int GetMonthDay(int year,int month)
	{
		assert(month > 0 && month < 13);
		static int days[13] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
		int day = days[month];
		if ((month == 2) && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
		{
			day += 1;
		}
		return day;
	}
	
	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);
	
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

然后浅浅写个+运算符重载:

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

会发现打印结果很微妙:

#include"Date.h"

int main()
{
	Date d1(1949, 12, 1);
	Date d2 = d1 + 49;
	d1.Print();
	d2.Print();
	return 0;
}

 

打印是打印了,但是原来的日期改变了,证明我们实现的不是+,而是+=

那怎样实现+呢?

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

//可以拷贝构造
Date Date::operator+(int day)
{
	Date tmp = Date(*this);
	tmp._day += day;
	while (tmp._day > GetMonthDay(tmp._year, tmp._month))
	{
		tmp._day -= GetMonthDay(tmp._year, tmp._month);
		tmp._month++;
		if (tmp._month > 12)
		{
			tmp._year++;
			tmp._month = 1;
		}
	}
	return tmp;
}

 蒽,确实不一样

 通过观察我们可以发现+和+=的代码差不多,可以进行一下代码复用

+复用+=:

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

//可以拷贝构造
Date Date::operator+(int day)
{
	Date tmp = Date(*this);
	tmp += day;
	return tmp;
}

 +=复用+:

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

Date& Date::operator+=(int day)
{
	*this = *this + day;
	return *this;
}

那到底是哪一种好呢?

其实是 +复用+=好一点,相应的和相应的比较:

两种+都一样,都产生了临时变量tmp,也都是传值返回,基本等价

但是+=不一样,直接实现的+=没有创建临时变量,但是复用+的+=产生了临时变量(+中药创建临时对象)

至此就已经基本上完全实现啦,这是完整代码:

Date.h:

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

class Date
{
public:
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	Date(const Date& tmp)
	{
		_year = tmp._year;
		_month = tmp._month;
		_day = tmp._day;
	}
	//获取某年某月天数
	int GetMonthDay(int year,int month)
	{
		assert(month > 0 && month < 13);
		static int days[13] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
		int day = days[month];
		if ((month == 2) && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
		{
			day += 1;
		}
		return day;
	}
	Date& operator++()
	{
		_day += 1;
		return *this;
	}
	Date operator++(int)
	{
		Date tmp = (*this);
		_day += 1;
		return tmp;
	}
	Date& operator--()
	{
		_day -= 1;
		return *this;
	}
	Date operator--(int)
	{
		Date tmp = (*this);
		_day -= 1;
		return tmp;
	}
	
	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);
	int operator-(const Date& d);
	
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
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;
}

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

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

Date Date::operator+(int day)
{
	Date tmp = Date(*this);
	tmp += day;
	return tmp;
}

Date& Date::operator-=(int 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 tmp(*this);
	tmp -= day;
	return tmp;
}

bool Date::operator<(const Date& d)
{
	if (_year > d._year)
	{
		return false;
	}
	if (_month > d._month)
	{
		return false;
	}
	if (GetMonthDay(_year, _month) > GetMonthDay(d._year, d._month))
	{
		return false;
	}
	return true;
}

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

	if (*this < d)
	{
		int flag = -1;
		max = d;
		min = *this;
	}
	int n = 0;
	while (min!=max)
	{
		min++;
		n++;
	}
	return n * flag;
}

Test.cpp:

#include"Date.h"

int main()
{
	Date d1(1949, 12, 1);
	Date d2(1949, 12, 2);
	cout << d1 - d2 << endl;
	d1.Print();
	d2.Print();
	return 0;
}

拜拜咯去吃鸭肠炒饭去 

回来就挨浇了我的天,本来只下了几滴,我在那嘲讽老天爷尿闭,结果刚说完它库库下

检查是否合法这样:

bool CheckInvalid()
{
	if (_year > 0||_month<1||_month>12||_day<1||_day>GetMonthDay(_year,_month))
	{
		return false;
	}
	else
	{
		return true;
	}
}

只好说再见了

  • 17
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python类和对象的练习题主要是通过编写类和方法来实现一些具体的功能。引用中给出了三个例子,分别是定义Point类并生成对象,实现两数之和的查找,以及实现一个函数来返回一个列表中最小的k个数。这些练习题可以帮助Python初学者更好地理解类和对象的概念,并提高编程能力。 1. 定义Point类并生成对象:这个练习题主要是让学生理解如何定义类和对象,并且掌握类的属性和方法的使用。在这个例子中,我们定义了一个Point类,它有两个属性x和y,以及一个方法saveInfo(),用于保存坐标信息。然后我们生成三个Point对象,并将它们放入一个列表中,最后打印出每个对象的属性值。 2. 实现两数之和的查找:这个练习题主要是让学生掌握字典的使用,以及如何在一个数组中查找两个数的和等于目标值。在这个例子中,我们定义了一个Solution类,它有一个方法twoSum(),用于查找两个数的和等于目标值。我们首先将数组中的数字作为key,下标作为value存到一个字典中,然后遍历数组,查找另外一个数字是否在字典中,如果在就可以直接返回value了。 3. 实现一个函数来返回一个列表中最小的k个数:这个练习题主要是让学生掌握列表的使用,以及如何实现一个函数来返回一个列表中最小的k个数。在这个例子中,我们定义了一个Solution类,它有一个方法mostCompetitive(),用于返回一个列表中最小的k个数。我们首先遍历列表,如果当前数字比下一个数字大,就将当前数字从列表中删除,然后继续遍历。最后返回列表中前k个数字即可。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值