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

C++初阶入门基础二——类和对象(中)

1类的默认成员函数

默认成员函数就是用户没有显式实现,编译器会自动生成的成员函数称为默认成员函数。一个类,我们不写的情况下编译器会默认生成以下6个默认成员函数,需要注意的是这6个中最重要的是前4个,最后两个取地址重载不重要,我们稍微了解一下即可。其次就是C++11以后还会增加两个默认成员函数,移动构造和移动赋值,这个我们后面再讲解。默认成员函数很重要,也比较复杂,我们要从两个方面去学习:

  • 第一:我们不写时,编译器默认生成的函数行为是什么,是否满足我们的需求。
  • 第二:编译器默认生成的函数不满足我们的需求,我们需要自己实现,那么如何自己实现?

2构造函数 

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

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

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

class Date
{
public:
	
	//带参构造函数
	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()
{
	//如果留下三个构造函数中的第二个带参函数,第一个和第三个注释掉
	//会编译报错:error C2512: “Date”: 没有合适的默认构造函数可用
	Date d1;
	d1.Print();
}

      

 编译器默认生成MyQueue的构造函数调用了Stack的构造,完成了两个成员的初始化:

struct Stack
{
public:
	Stack()
	{
		array = nullptr;
		capacity = _top = 0;
	}
	void push(int x)//
	{
		if (capacity == _top)
		{
			int newcapacity = capacity == 0 ? 4 : 2 * capacity;
			int* tmp = (int*)realloc(array, sizeof(int) * newcapacity);
			if (tmp == NULL)
			{
				perror("realloc fail!");
				exit(1);
			}
			array = tmp;
			capacity = newcapacity;
		}
		array[_top++] = x;

	}
	void Pop()
	{
		assert(_top > 0);
		--_top;
	}
	int Top()
	{
		assert(_top > 0);
		return array[_top - 1];
	}
	bool Empty()
	{
		return _top == 0;
	}
	void Destory()
	{
		free(array);
		array = nullptr;
		_top = capacity = 0;
	}
private:
	//成员变量
	int* array;
	int capacity;
	int _top;
};
class MyQueue
{
public:
	//编译器默认生成MyQueue的构造函数调用了Stack的构造,完成了两个成员的初始化
private:
	Stack pushst;
	Stack popst;
};
int main()
{
	MyQueue mq;
	return 0;
}

3析构函数 

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

  1. 析构函数名是在类名前加上字符~。
  2. 无参数无返回值。(这里跟构造类似,也不需要加void)
  3. 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。
  4. 对象生命周期结束时,系统会自动调用析构函数。
  5. 跟构造函数类似,我们不写编译器自动生成的析构函数对内置类型成员不做处理,自定类型成员会调用他的析构函数,
  6. 还需要注意的是我们显示写析构函数,对于自定义类型成员也会调用他的析构,也就是说自定义类型成员无论什么情况都会自动调用析构函数。
  7. 如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,如Date;如果默认生成的析构就可以用,也就不需要显示写析构,如MyQueue;但是有资源申请时,一定要自己写析构,否则会造成资源泄漏,如Stack。
  8. 一个局部域的多个对象,C++规定后定义的先析构。
    struct Stack
    {
    public:
    	Stack()
    	{
    		array = nullptr;
    		capacity = _top = 0;
    	}
    	~Stack()
    	{
    		cout << "Destory Stack" << endl;
    		free(array);
    		array = nullptr;
    		capacity = _top = 0;
    	}
    	void push(int x)//
    	{
    		if (capacity == _top)
    		{
    			int newcapacity = capacity == 0 ? 4 : 2 * capacity;
    			int* tmp = (int*)realloc(array, sizeof(int) * newcapacity);
    			if (tmp == NULL)
    			{
    				perror("realloc fail!");
    				exit(1);
    			}
    			array = tmp;
    			capacity = newcapacity;
    		}
    		array[_top++] = x;
    
    	}
    	void Pop()
    	{
    		assert(_top > 0);
    		--_top;
    	}
    	int Top()
    	{
    		assert(_top > 0);
    		return array[_top - 1];
    	}
    	bool Empty()
    	{
    		return _top == 0;
    	}
    private:
    	//成员变量
    	int* array;
    	int capacity;
    	int _top;
    };
    class MyQueue
    {
    public:
    	//编译器默认生成MyQueue的构造函数调用了Stack的构造,完成了两个成员的初始化
    	//编译器默认生成MyQueue的析构函数调用了Stack的析构,释放的Stack内部的空间
    	//显示写析构,也会自动调用Stack的析构
    private:
    	Stack pushst;
    	Stack popst;
    };
    int main()
    {
    	MyQueue mq;
    	return 0;
    }

    对比一下用C++和C语言实现Stack解决之前括号匹配问题isValid,我们发现有了构造函数和析构函数确实方便了很多,不会再忘记调用Init和Destory函数了,也方便了不少。

C++实现isVaild: 

#include<iostream>
#include<assert.h>
using namespace std;
class Stack
{
public:
	Stack()
	{
		array = nullptr;
		capacity = _top = 0;
	}
	~Stack()
	{
		cout << "Destory Stack" << endl;
		free(array);
		array = nullptr;
		capacity = _top = 0;
	}
	void push(int x)//
	{
		if (capacity == _top)
		{
			int newcapacity = capacity == 0 ? 4 : 2 * capacity;
			int* tmp = (int*)realloc(array, sizeof(int) * newcapacity);
			if (tmp == NULL)
			{
				perror("realloc fail!");
				exit(1);
			}
			array = tmp;
			capacity = newcapacity;
		}
		array[_top++] = x;

	}
	void Pop()
	{
		assert(_top > 0);
		--_top;
	}
	int Top()
	{
		assert(_top > 0);
		return array[_top - 1];
	}
	bool Empty()
	{
		return _top == 0;
	}
private:
	//成员变量
	int* array;
	int capacity;
	int _top;
};
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()
{
	const char s[15] = "{({}[])}";
	cout<<isValid(s)<<endl;
	return 0;
}

C语言实现isValid:

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct stack
{
	char* arr;
	int capacity;
	int top;
}st;
void stinit(st* ps);//初始化
void stdestroy(st* ps);//销毁
void stpush(st* ps, char x);//插入
bool stempty(st* ps);//判断栈是否为空
int stsize(st* ps);//得到栈此时有效元素的个数
int sttop(st* ps);//得到栈顶的元素
void stinit(st* ps)//
{
	assert(ps);
	ps->arr = NULL;
	ps->capacity = ps->top = 0;
}
void stdestroy(st* ps)//
{
	assert(ps);
	if (ps->arr)
		free(ps->arr);
	ps->arr = NULL;
	ps->top = ps->capacity = 0;
}
void stpush(st* ps, char x)//
{
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		char* tmp = (char*)realloc(ps->arr, sizeof(char) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail!");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newcapacity;
	}
	ps->arr[ps->top++] = x;

}
bool stempty(st* ps)
{
	assert(ps);
	return ps->top == 0;
}
void stpop(st* ps)
{
	assert(ps);
	assert(!stempty(ps));
	--ps->top;
}
int sttop(st* ps)
{
	assert(ps);
	assert(!stempty(ps));
	return ps->arr[ps->top - 1];
}
int stsize(st* ps)
{
	assert(ps);
	return ps->top;
}
bool isValid(const char* s)
{
	stack st;
	stinit(&st);
	while (*s)
	{
		if (*s == '[' || *s == '(' || *s == '{')
		{
			stpush(&st,*s);
		}
		else
		{
			//右括号比左括号多,数量匹配问题
			if (stempty(&st))
			{
				return false;
			}
			//栈里面取左括号
			char top = sttop(&st);
			stpop(&st);
			if ((*s == ']' && top != '[')
				|| (*s == '}' && top != '{')
				|| (*s == '(' && top != ')'))
			{
				stdestroy(&st);
				return false;
			}
		}
		++s;
	}
	//栈为空,返回真,说明栈都匹配 
	bool ret = stempty(&st);
	stdestroy(&st);
	return ret;
}
int main()
{
	char s[15] = "{()}";
	cout<<isValid(s)<<endl;
	return 0;
}

4拷贝构造函数

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

  1. 拷贝构造函数是构造函数的一个重载。
  2. 拷贝构造函数的第一个参数必须是类类型对象的引用,使用传值方式编译器直接报错,因为语法逻辑上会引发无穷递归调用。拷贝构造函数也可以多个参数,但是第一个参数必须是类类型对象的引用,后面的参数必须有缺省值。
  3. C++规定自定义类型对象进行拷贝行为必须调用拷贝构造,所以这里自定义类型传值传参和传值返回都会调用拷贝构造完成。
  4. 若未显式定义拷贝构造,编译器会生成自动生成拷贝构造函数。自动生成的拷贝构造对内置类型成员变量会完成值拷贝/浅拷贝(一个字节一个字节的拷贝),对自定义类型成员变量会调用他的拷贝构造。
  5. 像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器自动生成的拷贝构造就可以完成需要的拷贝,所以不需要我们显示实现拷贝构造。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器自动生成的拷贝构造完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。像MyQueue这样的类型内部主要是自定义类型Stack成员,编译器自动生成的拷贝构造会调用Stack的拷贝构造,也不需要我们显示实现MyQueue的拷贝构造。这里还有一个小技巧,如果一个类显示实现了析构并释放资源,那么他就需要显示写拷贝构造,否则就不需要。
  6. 传值返回会产生一个临时对象调用拷贝构造,传引用返回,返回的是返回对象的别名(引用),没有产生拷贝。但是如果返回对象是一个当前函数局部域的局部对象,函数结束就销毁了,那么使用引用返回是有问题的,这时的引用相当于一个野引用,类似一个野指针一样。传引用返回可以减少拷贝,但是一定要确保返回对象,在当前函数结束后还在,才能用引用返回。
    class Date
    {
    public:
    	Date(int year,int month,int day)
    	{
    		_year = year;
    		_month = month;
    		_day = day;
    	}
    	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 tmp(2025, 3, 24);
    	return tmp;
    }
    int main()
    {
    	Date d1(2025,3,24);
    	//C++规定自定义类型对象进行拷贝行为必须调用拷贝函数,所以这里传值传参要调用拷贝构造
    	//所以这里的d1传值传参给d要调用拷贝函数完成拷贝,传引用传参可以减少这里的拷贝
    	func1(d1);
    	cout << &d1 << endl;
    
    
    	//这里可以完成拷贝,但是不是拷贝构造,只是一个普通的构造
    	Date d2(&d1);
    
    
    	//这样写才是拷贝构造,通过同类型的对象初始化构造,而不是指针
    	Date d3(d1);
    	Date d4 = d1;
    
    
    	//func2返回了一个局部对象tmp的引用作为返回值
    	//func2函数结束,tmp对象就销毁了,相当于一个野引用
    	Date ret = func2();
    	ret.Print();
    	return 0;
    }
    class Stack
    {
    public:
    	Stack()
    	{
    		array = nullptr;
    		capacity = _top = 0;
    	}
    	Stack(const Stack& st)
    	{
    		array = (int*)malloc(st.capacity * sizeof(int));
    		if (nullptr == array)
    		{
    			perror("malloc申请失败");
    			return;
    		}
    		memcpy(array, st.array, sizeof(int) * st._top);
    		_top = st._top;
    		capacity = st.capacity;
    	}
    	~Stack()
    	{
    		cout << "Destory Stack" << endl;
    		free(array);
    		array = nullptr;
    		capacity = _top = 0;
    	}
    	void push(int x)//
    	{
    		if (capacity == _top)
    		{
    			int newcapacity = capacity == 0 ? 4 : 2 * capacity;
    			int* tmp = (int*)realloc(array, sizeof(int) * newcapacity);
    			if (tmp == NULL)
    			{
    				perror("realloc fail!");
    				exit(1);
    			}
    			array = tmp;
    			capacity = newcapacity;
    		}
    		array[_top++] = x;
    
    	}
    	void Pop()
    	{
    		assert(_top > 0);
    		--_top;
    	}
    	int Top()
    	{
    		assert(_top > 0);
    		return array[_top - 1];
    	}
    	bool empty()const
    	{
    		return _top == 0;
    	}
    private:
    	//成员变量
    	int* array;
    	int capacity;
    	int _top;
    };
    class MyQueue
    {
    public:
    private:
    	Stack pushst;
    	Stack popst;
    
    };
    int main()
    {
    	Stack st1;
    	st1.push(1);
    	st1.push(2);
    	//Stack不显示实现拷贝构造,用自动生成的拷贝构造完成浅拷贝
    	//会导致st1和st2里面的_array指针指向同一块资源,析构时会析构两次,程序崩溃
    	Stack st2 = st1;
    
    	MyQueue mq1;
    	//MyQueue自动生成的拷贝构造,会自动调用Stack拷贝构造完成pushst/popst
    	//的拷贝,只要Stack拷贝构造自己实现了深拷贝,MyQueue的拷贝就没问题
    	MyQueue mq2 = mq1;
    	return 0;
    }

5赋值运算符重载

5.1运算符重载

  • 当运算符被用于类类型的对象时,C++语言允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象使用运算符时,必须转换成调用对应运算符重载,若没有对应的运算符重载,则会编译报错。
  • 运算符重载是具有特殊名字的函数,他的名字是由operator和后面要定义的运算符共同构成。和其他函数一样,它也具有其返回类型和参数列表以及函数体。
  • 重载运算符函数的参数个数和该运算符作用的运算对象数量一样多。一元运算符有一个参数,二元运算符有两个参数,二元运算符的左侧运算对象传给第一个参数,右侧运算对象传给第二个参数。。如果一个重载运算符函数是成员函数,则它的第一个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数比运算对象少一个。
  • 运算符重载以后,其优先级和结合性与对应的内置类型运算符保持一致。
  • 不能通过连接语法中没有的符号来创建新的操作符:比如operator@。
  • .*     ::  sizeof    ?:   .注意以上5个运算符不能重载。(选择题里面常考,大家要记一下)
  • 重载操作符至少有一个类类型参数,不能通过运算符重载改变内置类型对象的含义,如:int operator+(int x, int y)
  • 一个类需要重载哪些运算符,是看哪些运算符重载后有意义,比如Date类重载operator就有意义,但是重载operator+就没有意义。
  • 重载++运算符时,有前置++和后置++,运算符重载函数名都是operator++,无法很好的区分。C++规定,后置++重载时,增加一个int形参,跟前置++构成函数重载,方便区分。
  • 重载<<和>>时,需要重载为全局函数,因为重载为成员函数,this指针默认抢占了第一个形参位置,第一个形参位置是左侧运算对象,调用时就变成了对象<cout,不符合使用习惯和可读性。重载为全局函数把ostream/istream放到第一个形参位置就可以了,第二个形参位置当类类型对象。

例子如下: 

class Date
{
public:
	Date(int year,int month,int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	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;
};
//编译报错:“operator +”必须至少有一个类类型的形参
//int operator+(int x, int y)
//{
//	return x + y;
//}
bool operator==(const Date& d1, const Date& d2)
{
	return d1._year == d2._year &&
		d1._month == d2._month&&
		d1._day==d2._day;
}
int main()
{

	return 0;
}

 以上代码面临问题:成员变量是私有的,会报错:

解决问题有以下几个方法:

  1. 成员放共有。
  2. date提供getxxx函数
  3. 友元函数
  4. 重载为成员函数 

第四种:

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;
	}
	bool operator==(const Date& d)
	{
		return this->_year == d._year &&
			this->_month == d._month &&
			(*this)._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;
};
//编译报错:“operator +”必须至少有一个类类型的形参
//int operator+(int x, int y)
//{
//	return x + y;
//}
int main()
{
	Date d1;
	Date d2;
	//运算符重载函数可以显示使用
	d1.operator==(d2);

	//编译器会换成d1.operator==(d2);
	d1 == d2;

	return 0;
}

5.2赋值运算符重载 

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

  1. 赋值运算符重载是一个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成const 当前类类型引用,否则会传值传参会有拷贝
  2. 有返回值,且建议写成当前类类型引用,引用返回可以提高效率,有返回值目的是为了支持连续赋值场景。
  3. 没有显式实现时,编译器会自动生成一个默认赋值运算符重载,默认赋值运算符重载行为眼默认拷贝构造函数类似,对内置类型成员变量会完成值拷贝/浅拷贝(一个字节一个字节的拷贝),对自定义类型成员变量会调用他的赋值重载函数。
  4. Date这样的类成员变量全是内置类型且没有指向什么资源编译器自动生成的赋值运算符重载就可以完成需要的拷贝,所以不需要我们显示实现赋值运算符重载。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器自动生成的赋值运算符重载完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。像MyQueue这样的类型内部主要是自定义类型Stack成员,编译器自动生成的赋值运算符重载会调用Stack的赋值运算符重载,也不需要我们显示实现MyQueue的赋值运算符重载。这里还有一个小技巧,如果一个类显示实现了析构并释放资源,那么他就需要显示写赋值运算符重载,否则就不需要。
    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;
    	}
    	void Print()
    	{
    		cout << _year << '/' << _month << '/' << _day << '/' << endl;
    	}
    	Date& operator=(const Date& d)
    	{
    		//要检查自己给自己赋值的情况
    		if(this != &d)
    		{
    			_year = d._year;
    			_month = d._month;
    			_day = d._day;
    		}
    		//d1=d2的返回对象应该d1,也就是*this
    		return *this;
    	}
    private:
    	int _year;
    	int _month;
    	int _day;
    };
    
    int main()
    {
    	Date d1;
    	Date d2(2025,3,24);
    	d1 = d2;
    	d1.Print();
    
    	//需要注意这里是拷贝构造,不是赋值重载
    	//复制重载是两个已经存在的对象进行的拷贝赋值
    	//拷贝构造是对一个对象拷贝初始化给一个即将创建的新对象
    	Date d3 = (d2);
    	return 0;
    }

5.3日期类实现 

5.3.1Date.h:

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
class Date
{
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);
public:
	bool CheckDate();
	int GetMonthDay(int year, int month)
	{
		static int day[13] = { -1,31,28,31,30,31,30,31,31,30,31,30,31 };
		int ret = day[month];
		if (month == 2 && (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
		{
			ret = 29;
		}
		return ret;
	}
	Date(int year=1, int month=1, int day=1);
	Date(const Date& d);
	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;
	//加减天数,原对象变了
	Date& operator+=(int x);
	Date& operator-=(int x);
	//加减天数,原对象不变
	Date operator+(int x);
	Date operator-(int x); 
	//第一个前置++,第二个后置++
	Date& operator++();
	Date operator++(int);
	//第一个前置--,第二个后置--
	Date& operator--();
	Date operator--(int);
	//日期减日期
	int operator-(const Date& d)const;
	void Print()const;
private:
	int _year;
	int _month;
	int _day;
};

5.3.2Date.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;
	}
}
Date::Date(const Date& d)
{
	_year = d._year;
	_month = d._month;
	_day = d._day;
}
void Date::Print()const
{
	cout << _year << '/' << _month << '/' << _day << '/' << endl;
}
Date& Date::operator=(const Date& d)
{
	//要检查自己给自己赋值的情况
	if (this != &d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	//d1=d2的返回对象应该d1,也就是*this
	return *this;
}
bool Date::operator==(const Date& d)const
{
	return this->_year == d._year &&
		this->_month == d._month &&
		(*this)._day == d._day;
}
bool Date::operator<(const Date& d) const
{
	if (this->_year < d._year)
	{
		return true;
	}
	else if ((this->_year == d._year) && (this->_month < d._month))
		return true;
	else if ((this->_month == d._month) && (this->_day < d._day))
		return true;
	else
		return false;
}
bool Date::operator>(const Date& d)const
{
	if (*this < d || *this == d)
		return false;
	else
		return true;
}
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 !(*this == d);
}
Date& Date::operator+=(int x)
{
	if (x < 0)
	{
		return *this -= -x;
	}
	this->_day += x;
	while (this->_day > GetMonthDay(_year,_month))
	{
		_day -= GetMonthDay(_year,_month);
		_month++;
		if (_month == 12)
		{
			_month = 1;
			_year++;
		}
	}
	return *this;
}
Date& Date::operator-=(int x)
{
	if (x < 0)
	{
		return *this += -x;
	}
	this->_day -= x;
	while (this->_day <=0)
	{
		_month--;
		if (_month == 0)
		{
			_month = 12;
			_year--;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}
Date Date::operator+(int x)
{
	Date tmp = *this;
	tmp += x;
	return tmp;
}
Date Date::operator-(int x)
{
	Date tmp = *this;
	tmp -= x;
	return tmp;
}
Date Date::operator++(int)
{
	Date tmp = *this;
	tmp += 1;
	return tmp;
}
Date& Date::operator++()
{
	*this += 1;
	return *this;
}
Date& Date::operator--()
{
	*this -= 1;
	return *this;
}
Date Date::operator--(int)
{
	Date tmp = *this;
	tmp -= 1;
	return tmp;
}
istream& operator>>(istream& in, Date& d)
{
	cout << " 请输入日期->"<<endl;
	in >> d._year >> d._month  >> d._day;
	if (!d.CheckDate())
	{
		cout << "日期非法" << endl;
	}
	return in;
}
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 ret = 0;
	while (max != min)
	{
		++min;
		ret++;
	}
	return ret;
}
ostream& operator<<(ostream& out, const Date& d)
{
	out << d._year << "年" << d._month << "月" << d._day << "日"<<endl;
	return out;
}

6取地址运算符重载 

6.1const成员函数

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

6.2取地址运算符重载                                                                 

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

 

相关文章:

  • 避免踩坑!查收查引常见问题解答
  • C语言动态内存管理深度解析与嵌入式开发实战
  • 12_JavaScript_实现日期
  • dfs(深度优先)——太抽象了
  • 【新能源汽车实验室设备控制:PLC与单片机选型指南(深度解析+实战案例)】
  • AI数字人直播系统
  • java中的枚举类型和c,c++的有区别吗?c,c++的枚举,结构体,联合体,三种数据有什么区别和联系
  • 基于DrissionPage的TB商品信息采集与可视化分析
  • 《大语言模型》学习笔记(四)--Transformer 模型
  • 数据库 第一章 MySql基础(1)
  • Thales靶机渗透攻略
  • 蓝桥杯备考----> Apple Catching G(线性DP)
  • 01LinePlot
  • 【蓝桥杯速成】| 12.回溯排列N皇后
  • leetcode day30 134+135+860
  • 深挖增长内核:好产品驱动增长的全方位解析
  • 深度解析:TOML、XML、YAML及其他配置/数据格式对比
  • 用YoloV8训练一个图片检测的模型,我接下来要做哪些事
  • 《深入Linux内核架构》读书笔记--第三章 内存管理
  • 【含文档+PPT+源码】基于Python的全国景区数据分析以及可视化实现
  • 坚决打好产业生态培育攻坚战!陈吉宁调研奉贤区
  • 习近平就乌拉圭前总统穆希卡逝世向乌拉圭总统奥尔西致唁电
  • 时隔三年,俄乌直接谈判重启
  • 圆桌丨新能源车超充技术元年,专家呼吁重视电网承载能力可能面临的结构性挑战
  • 一船明月过沧州:为何这座城敢称“文武双全”?
  • 青海省交通运输厅副厅长田明有接受审查调查