【C++】—— 类和对象(中)一张图带你搞清楚6个默认成员函数+万字总结 复习全靠它

 

目录

值得收藏

类的6个默认成员函数

一、构造函数

1.概念

2.构造函数的特性

3. 显示定义与未显示定义构造函数

二、析构函数 

1.概念

2.析构函数的特性 

三、拷贝构造函数 

1.概念 

2.拷贝构造函数的特性 

3.拷贝构造的注意点

四、赋值运算符重载 

1.运算符重载 

1.概念

2.如何定义及使用

2.赋值运算符重载 

 1.概念

五、日期类实现

1. 日期类的定义

2.日期类的接口实现 

①日期类的构造函数

②日期类比较运算符重载 

③日期类+、-、+=、-=运算符重载

④日期类++、-- 重载

⑤日期 - 日期及获取某天是周几 

⑥对流插入和流提取的重载 

六、const修饰类的成员函数 

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


值得收藏 

以下是默认成员函数的思维导图总结:

类的6个默认成员函数

        如果一个类中什么成员都没有,简称为空类。空类中什么都没有吗?并不是的,任何一个类在我们不写的情况下,都会自动生成下面6个默认成员函数;

一、构造函数

1.概念

        在类与对象(上)中,我们对类有了一定的概念, 简单的将类内部分为两块:公有和私有;以Date类为例,当我们实例化出一个对象时,需要对类Date内部的成员变量初始化时,就需要在类Date给一个公有的成员函数,这样才能访问到类内部的私有成员变量;只要每次实例化出一个对象时,都会去手动调用该方法(函数)进行初始化,未免有些麻烦;

//定义了一个类--Date
class Date
{ 
//公有
public:
     void SetDate(int year, int month, int day)
     {
         _year = year;
         _month = month;
         _day = day;
     }
 
     void Display()
     {
         cout <<_year<< "-" <<_month << "-"<< _day <<endl;
     }
//私有
private:
     int _year;
     int _month;
     int _day;
};
int main()
{
     Date d1;//实例化出一个对象,d1
     d1.SetDate(2018,5,1);//手动初始化第一次
     d1.Display();
 
     Date d2;//实例化出一个对象,d2
     d2.SetDate(2018,7,1);//手动初始化第二次
     d2.Display();
     return 0; 
}

为了解决这样的问题,在C++中就有了构造函数的概念;

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

2.构造函数的特性

        构造函数 是特殊的成员函数,需要注意的是,构造函数的虽然名称叫构造,但是需要注意的是构造函数的主要任务并 不是开空间创建对象 ,而是 初始化对象

定义如下: 

 Data( )

/*构造函数*/
class Date
{
public:
    //以下是自己创建的两个构造函数,分别为无参的和带参的
	Date()//函数名和类名相同,无返回值---无参调用
	{
		_year = 0;
		_month = 1;
		_day = 5;
	}
	Date(int year, int month, int day)//函数名和类名相同,无返回值---带参调用
	{
		_year = year;
		_month = month;
		_day = day;
	}

private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1;//自动调用无参的构造函数

	Date d2(2022, 1, 5);//自动调用带参的构造函数

    // 注意:如果通过无参构造函数创建对象时,对象后面不用跟括号,否则就成了函数声明
    // 以下代码的函数:声明了d3函数,该函数无参,返回一个日期类型的对象
    Date d3();
	return 0;
}

在【C++】快速入门 的博客中,我们了解了缺省的概念,发现上面的代码中,无参和带参的构造函数可以利用缺省将这两个函数写成一个,这里代码就可以简化为:

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

    //利用缺省将上面的代码转换为下面的代码
    
	Date(int year = 0, int month = 1, int day = 5)
	{
		_year = year;
		_month = month;
		_day = day;
	}

3. 显示定义与未显示定义构造函数

         如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成。
        简单的讲就是,你觉得编译器默认生成的构造函数不是你想要达到的效果,你就自己定义(显示定义),你觉得编译器默认生成的构造函数够用了,满足条件,就不用自己定义了(未显示定义);
/*如果没有显示定义构造函数,会发生什么情况呢*/
class Date
{
public:
    /*
        未显示定义构造函数

    */

private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1;
	return 0;
}

        构造函数本来主要是完成初始化工作的,通过上面的调试图却发现,它并没有对成员变量进行初始化, 其实并不是构造函数一点用处都没有;

对于构造函数它是这么规定的:

C++里面把类型分为两类:内置类型(基本类型),自定义类型
内置类型:int/char/double/指针/内置类型数组 等等
自定义类型:struct/class定义的类型
我们不写编译器默认生成构造函数,对于内置类型不做初始化处理
对于自定类型成员变量会去调用它的默认构造函数初始化,如果没有默认构造函数就会报错
任何一个类的默认构造函数就是--不用参数就可以调用。
任何一个类的默认构造函数有三个,全缺省、无参、我们不写编译器默认生成的。(
只能存在一个)

class A
{
public:
	A()
	{
		cout << " A()" << endl;
		_a = 0;
	}

	/*A(int a )
	{
		cout << " A()" << endl;
		_a = a;
	}*/
private:
	int _a;
};

class Date
{
public:
	/*
	   未显示定义构造函数

	*/
private:
    //内置类型
	int _year;
	int _month;
	int _day;
    
    //自定义类型
	A _aa;
};

int main()
{
	Date d1;
	return 0;
}

如果A里没有默认构造函数,而是带参的构造函数,程序就会报错;

强调:构造函数不是常规的函数,不可以按如下的方式调用 

d1.Date();

二、析构函数 

1.概念

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

2.析构函数的特性 

 定义如下:

 ~Data( )

class Data
{
public:
    //构造函数
	Data(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
    //析构函数
	~Data()
	{
		cout << '1' << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Data d1;
	Data d2(2022, 1, 15);

	return 0;
}

        通过调试发现,d1和d2确实是调用了析构函数,但是对于Date类并没有什么资源需要清理,也不是想象中那样将成员变量置成随机值;所以这里给不给析构函数都是可以的,难道析构函数也没啥用处吗?其实不然。

析构函数构造函数有类似的特性:

        如果我们不写析构函数和构造类函数类似,对于内置类型成员变量不作处理,对于自定义类型成员变量会去调用它的析构函数;

 通过下面的例子看看析构函数的用处:

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

class Stack
{
public:
	Stack(int capacity = 4)
	{
		_a = (int*)malloc(sizeof(int));
		if (_a == nullptr)
		{
			cout << "malloc fail\n" << endl;
			exit(-1);
		}
		_top = 0;
		_capacity = capacity;
	}
	//如果我们不写析构函数和构造类函数类似
	//对于内置类型成员变量不作处理
	//对于自定义类型成员变量会去调用它的析构函数
	~Stack()
	{
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}
private:
	int* _a;
	size_t _top;
	size_t _capacity;
};

class MyQueue 
{
public:
private:
	Stack pushST;
	Stack popST;
};

int main()
{
	Data d1;
	Data d2(2022, 1, 15);

	Stack s1;
	Stack s2(20);
	/*先析构s2->s1->d2->d1*/

	MyQueue mq;

	return 0;
}

这段代码实现的是用栈实现队列, 调试分析如下:

上述代码中有5个对象,d1、d2、s1、s2、mq;他们的析构顺序如何呢?

对象的创建是在栈中的,所有先创建的后析构、后创建的先析构,顺序为:mq、s2、s1、d2、d1

三、拷贝构造函数 

1.概念 

        从拷贝这个词就可以想到,当我们在临近交作业的时候,尤其是电子档的作业时,发现作业太多,不想思考,于是就有了copy的想法;从而就产生了两个一模一样的作业,当然也有可能是一人干活,全班享受啦^-^(但是不建议大家copy)
        那在创建对象时,可否创建一个与一个对象一某一样的新对象呢? 当然是可以的;
        那就需要用到拷贝构造函数啦;

2.拷贝构造函数的特性 

定义如下: 

 Data(const Data& d)

class Date
{
public:
	/*构造函数*/
	Date(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	/*拷贝构造函数*/
	Date(const Data& d)
	{
		//加const为了防止写成 d._year = _year;
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
private:
	int _year;
	int _month;
	int _day;
};


int main()
{
	Date d1(2022, 1, 15);

	//拷贝复制
	Date d2(d1);//调用拷贝构造---自定义类型用一个同类型的对象初始化我,就是拷贝构造
	
	return 0;
}

通过上图的分析,拷贝构造函数是必须引用传参的,为了防止被拷贝的对象被修改,加上const进行修饰;

拷贝构造函数与前两个函数一样,如果不写拷贝构造,系统会自动生成默认拷贝构造函数 ;

1.对于内置类型成员,会完成按字节序的拷贝;(称为浅拷贝)
2.对于自定义类型成员,会调用他的拷贝构造;

3.拷贝构造的注意点

以下是关于栈类的拷贝构造

class Stack
{
public:
    //构造函数
	Stack(int capacity = 4)
	{
		_a = (int*)malloc(sizeof(int));
		if (_a == nullptr)
		{
			cout << "malloc fail\n" << endl;
			exit(-1);
		}
		_top = 0;
		_capacity = capacity;
	}

    //拷贝构造函数
    /*

        编译器默认生成

    */

    //析构函数
	~Stack()
	{
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}
private:
	int* _a;
	size_t _top;
	size_t _capacity;
};


int main()
{

	/*直接崩溃*/
	//导致他们指向的空间被析构两次,导致程序崩溃
	Stack st1(10);
	Stack st2(st1);

	return 0;
}

        对于栈类的拷贝构造,因为我们没有定义,编译器回去默认生成一个拷贝构造函数,实例化出st1对象后进行了一个初始化,然后对st2对象进行拷贝构造,此时并不存在任何问题,但是他们都需要进行一次析构函数,对资源进行清理;就在这个时候出现了问题; 

四、赋值运算符重载 

1.运算符重载 

1.概念

        对于内置类型的大、小进行比较,编译器可以直接处理 ,但是对于自定义类型编译不能直接处理; 

        比如我们定义了一个日期类,实例化出两个对象后,想要比较一下两个对象中的天数大小时,直接用运算符是完全可以的,但是想要比较d1和d2两个自定义类型的大小时,使用运算符是会发生错误的;

class Data
{
public:
	Data(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

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

int main()
{
	Data d1(2022, 1, 16);
	Data d2(2022, 1, 31);

	int ret = d1._day > d2._day;
	cout << ret << endl;
    //d1 > d2;报错

	return 0;
}

        对于以上的情况,C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。
函数名字为:关键字 operator 后面接需要重载的 运算符符号 。(如 operator>
函数原型:返回值类型 operator操作符(参数列表)
注意:
1.不能通过连接其他符号来创建新的操作符:比如 operator@
2.重载操作符必须有一个类类型或者枚举类型的操作数
3.用于内置类型的操作符,其含义不能改变,例如:内置的整型+,不能改变其含义
4.作为类成员的重载函数时,其形参看起来比操作数数目少1成员函数的 操作符有一个默认的形参this,限定为第一个形参
5.  .* :: sizeof ? : (三目操作符)、 . 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。

2.如何定义及使用

1.在类外定义(需要将成员变量改为共有)

/*运算符重载*/
class Data
{
public:
	Data(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

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

/*****类外定义******/

//函数名 operator操作符
//返回类型:看操作符运算后返回值是什么
//参数:操作符有几个操作数,他就有几个参数
bool operator>(const Data& d1, const Data& d2)
{
	if (d1._year > d2._year)
	{
		return true;
	}
	else if (d1._year == d2._year && d1._month > d2._month)
	{
		return true;
	}
	else if (d1._year == d2._year && d1._month == d2._month && d1._day > d2._day)
	{
		return true;
	}
	else
	{
		return false;
	}
}


int main()
{
	Data d1(2022, 1, 16);
	Data d2(2022, 1, 31);


	//默认情况下,C++是不支持自定义类型对象使用运算符
	d1 > d2;//编译器看到这个就会将其转换为operator>(d1,d2),就像函数调用一样
	cout << (d1 > d2) << endl;
	cout << operator>(d1, d2) << endl;
	return 0;
}

对于这个函数的参数个数来说,操作符有几个操作数,参数就有几个,既然能在类内定义会发生怎样的变化呢?

2.在类内定义 

class Date
{
public:
	Date(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	//bool operator>(const Date& d1, const Date& d2)
	//按照这样去写,是错误的,操作数过多,因为隐含了一个this指针
	//d1.operator > (d2); bool operator>(const Date* this, const Date& d2)  
	//d1就传给了this,d2就传给了d2
	bool operator>(const Date& d2)
	{
		if (_year > d2._year)
		{
			return true;
		}
		else if (_year == d2._year && _month > d2._month)
		{
			return true;
		}
		else if (_year == d2._year && _month == d2._month && _day > d2._day)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
private:
	int _year;
	int _month;
	int _day;
};


int main()
{
	Date d1(2022, 1, 16);
	Date d2(2022, 1, 31);
	d1 > d2;//先去类看有没有这个运算符,没有去全局找  运算符重载一般重载为成员函数,为了解决访问私有变量的问题
	//d1.operator > (d2);类里面转换为这样
	
	return 0;
}

如果直接将刚才类外定义函数直接放到类内去, 会导致操作数过多,我们直到类里面隐含了一个this指针;

在类外定义的时候,是不存在this指针的,函数有两个参数:

bool operator>(const Data& d1, const Data& d2);

d1 > d2;//编译器会转换为operatot>(d1,d2);
//d1传给const Data& d1;d2传给const Data& d2

在类内定义的时候由于this指针的存在,强行将上面的代码放到类内,此时形参就变成三个:

bool operator>(const Date& d1, const Date& d2);//在类外时

d1 > d2;//编译器会转换为operatot>(d1,d2);
//d1传给const Date& d1;d2传给const Date& d2

bool operator>(const Date* this,const Data& d1, const Data& d2);//在类内时
d1 > d2;//编译器会转换为d1.operatot>(d2);
//这里就会导致操作数过多

虽然在类外定义可以实现,但是破破坏了类的封装性,所以在类内定义时,我们只要给一个参数就可以了; 

2.赋值运算符重载 

 1.概念

        赋值运算符重载实现的是两个自定义类型的对象之间的赋值,它和拷贝构造函数不同的是:

        1.拷贝构造是用一个已存在的对象去初始化一个对象;

        2.赋值运算符重载是两个已存在的对象进行赋值操作;

class Date
{
public:
    //构造函数
	Date(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
    //拷贝构造
	Date(const Date& d)
	{
		cout << " 11111 " << endl;
	}

    //赋值运算符重载
	//d1 = d3;
	Date operator=(const Date& d)
	{
		//防止有人d1=d1
		//极端情况下自己给自己赋值,判断一下地址就直接跳过了
		if (this != &d)
		{
			_year = d._year;
			_month = d._month;
			_day = d._day;
		}
		return *this;
	}

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


int main()
{
	Date d1(2022, 1, 16);
	Date d2(2022, 1, 31);
	Date d3(2022, 2, 26);

	//一个已经存在的对象拷贝初始化一个马上创建实例化的对象
	Date d4(d1);//拷贝构造
	Date d5 = d1;

	//两个已经存在的对象,之间进行赋值拷贝
	d2 = d1 = d3;
	//d1.operator=(d3);
	//d2.operator=(d1.operator=(d3));

	return 0;
}

因为赋值运算符重载也是在类内定义的,这里只需要给一个参数就可以;

        在类中如果如果没有显示定义赋值重载函数,编译器也会在类中默认 生成一个赋值重载函数,对于内置类型的成员采用浅拷贝,对于自定义类型的成员会去调用它的赋值重载函数;

五、日期类实现

1. 日期类的定义

class Date
{

public:
    //构造函数
	Date(int year = 1, int month = 1, int day = 1);

	//打印
	void Print() const;

	// 获取某年某月的天数
	int GetMonthDay(int year, int month);

	// >运算符重载
	bool operator>(const Date& d);
	// <运算符重载
	bool operator<(const Date& d);
	// >=运算符重载
	bool operator>=(const Date& d);
	// <=运算符重载
	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);
	
	// 前置++
	Date& operator++();

	// 后置++; 后置为了跟前置++,进行区分,增加了一个参数占位,跟前置++,构成重载
	Date operator++(int);
	// 前置--
	Date& operator--();

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

	// 日期-日期 返回天数
	int operator-(const Date& d);

	//获取某天是周几
	void PrintWeekDay();

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

2.日期类的接口实现 

①日期类的构造函数

        对于日期类,我们要对它的年、月、日进行初始化,我们可以采用全缺省的方式;一年有12个月,每个月的天数是不一样的,我们可以用一个数组来表示,最好给一个静态的数组,因为当我们每次实例化对象时,静态的数组只会初始化一次;但是此时还要考虑:给定的年月日是否合法和闰年、非闰年二月的天数情况。

        年的判断一定大于等于0、月一定是(0,12)、天数最主要的就是二月(闰年的判断);

        方法:

        1.可以采用if、else判断条件,把所有的情况都列举出来;

        2.也可以采用switch语句;相比第一种要好一些;

        3.就是用数组加上闰年的判断条件;对于数组个数,最好给到13个,下标是从0开始的,第一个元素就放0,后面的12个放相应月的天数,二月给28,当判断为闰年时,直接加1就可以了;因为是对类的私有成员的访问,我们将其实现为成员函数;

// 获取某年某月的天数
int Date::GetMonthDay(int year, int month)const
{
	static int monthDayArray[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	int day = monthDayArray[month];//获取每个月的天数
	if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
	{
		day += 1;//如果是二月并且是闰年,天数就加+1
	}
	return day;
}

//构造函数
Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;
	if (!(_year >= 0
		&& (month > 0 && month < 13)
		&& (day > 0 && day <= GetMonthDay(year, month))))
	{
        //不满足年月日的条件,就是非法的
		cout << "非法日期->";
		Print();
	}
}

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

②日期类比较运算符重载 

        对于日期类的运算符重载,不难实现;需要注意的地方:有6个比较运算符,我们只需要实现其中两个运算符(>和==),其他的直接复用即可;

// >运算符重载
bool Date::operator>(const Date& d)const
{
	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;
	}
	else
	{
		return false;
	}
}

// ==运算符重载
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
{
	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);
}

③日期类+、-、+=、-=运算符重载

        在代码实现之前,我回顾一下 +、-、+=、-= 这些运算符运算结果有什么不同?

在定义了 int i = 1;那么i + 1;和i += 1;的含义是不同的;前者i的值并没有改变,后者i的值变成了2;

日期 += 天数:

        如果有个合法的日期,当需要计算100天后(假设)的日期时,当月的天数加满后就要给月进位,只要天数不合法,月就要进位,当月进位到13时,就给年进位,月份置1;

日期 + 天数:

        日期 += 天数改变了原来的日期,当你想要直到100天后的日期并且不改变当前日期时,就需要用 + ;通过实例化临时对象拷贝构造原来的日期,复用日期 += 天数的函数进行计算,既得到了100天后的日期,又不会对原来的日期进行改变;

日期 -= 天数 和 日期 - 天数,和上面的类似;

注意:

        1.如果使用+=时,给的天数是-100时,一定会存在错误;-100表面想要得到当前日期向前100天的日期;

        2.如果使用-=时,给的天数是-100时,一定会存在错误;-100表面想要得到当前日期向后100天的日期;

        对于以上两种情况,必须要加以判断

// 日期 += 天数
Date& Date::operator+=(int day)
{
	if (day < 0)
	{
		return *this -= -day;//如果传过来的天数是负数,实际上就是调用-=,把天数变为正数
	}
	_day += day;//先将天数加上
	while (_day > GetMonthDay(_year, _month))
	{
        //凑满本月天数,月进位1
		_day -= GetMonthDay(_year, _month);
		++_month;
        //如果月进位到13时,年进位,月置1
		if (_month == 13)
		{
			_month = 1;
			_year++;
		}
	}
	return *this;
}

// 日期 + 天数
Date Date::operator+(int day)const
{
	Date ret(*this);
	//ret.operator+=(day);
	ret += day;
	return ret;
}

// 日期 -= 天数
Date& Date::operator-=(int day)
{
	if (day < 0)
	{
		return *this += -day;//如果传过来的天数是负数,实际上就是调用+=,把天数变为正数
	}

	_day -= day;//先将天数减去
	while (_day <= 0)
	{
        //向月借位
		--_month;
        //当月借完后,就要向年借位,并把月置1
		if (_month == 0)
		{
			--_year;
			_month = 12;
		}
        //加上当月的天数,直到天数符合条件
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}

// 日期 - 天数
Date Date::operator-(int day)const
{
	Date ret(*this);
	ret -= day;
	return ret;
}

④日期类++、-- 重载

后置为了跟前置,进行区分,增加了一个int参数占位;跟前置,构成重载 ;

对于前置++和--而言,返回的是++或--之的值;

对于后置++和--而言,返回的是++或--之的值;

所以对于后置的操作,我们也需要临时的变量进行保存*this,改变*this后,返回临时的变量即可;

// 前置++
Date& Date::operator++()
{
	*this += 1;
	return *this;
}

// 后置++
Date Date::operator++(int)
{
	Date ret(*this);
	//Date ret = *this;
	*this += 1;
	return ret;
} 

// 前置--
Date& Date::operator--()
{
	*this -= 1;
	return *this;
}

// 后置--
Date Date::operator--(int)
{
	Date ret(*this);
	//Date ret = *this;
	*this -= 1;
	return ret;
}

一般更倾向于使用前置;后置比前置多了一些构造和析构操作; 

⑤日期 - 日期及获取某天是周几 

// 日期-日期 返回天数
int Date::operator-(const Date& d)
{
    //定义出大日期与小日期(假设)
	Date max = *this;
	Date min = d;
	int flag = 1;
    //先进行大小日期的判断,不符合则交换
	if (*this < d)
	{
		max = d;
		min = *this;
		flag = -1;// 这里flag的作用:如果是小日期-大日期,应该是负数
	}
	int count = 0;
	while (min != max)
	{
        //让小日期不断的累加,count记录天数
		++min;
		++count;
	}
	return count * flag;
}

//获取某天是周几
void Date::PrintWeekDay()const
{
	const char* arr[] = { "周一","周二", "周三", "周四", "周五", "周六", "周日" };
	/*Date start(1900, 1, 1);
	int count = *this - start;*/
	int count = *this - Date(1900, 1, 1);//匿名对象
	cout << arr[count % 7] << endl;
}

⑥对流插入和流提取的重载 

对于上面的操作都是将日期给定好的,那么如何输入一个日期并输出出来呢?

 如果直接实例化出一个对象,按部就班的进行输入和输出,会发现出问题了;此时就需要流插入和流提取的重载

operator>>(); //流提取操作符重载

operator<<(); //流插入操作符重载

其实cout和cin是一个全局类型的对象,cout的类型是ostream、cin的类型是istream

按照刚才的那些运算符重载,这个也就可以定义为这样:

void operator<<(ostream& in);//定义

cin>>d1;//但是这里调不动

d1.operator<<(cin);//但是这里调用是没问题的
//上面的不就是:d1>>cin;

这种两种方式为什么存在差异呢?

        因为成员函数有隐含的this指针存在,那么cin>>d1;在传参时是把cin传给了this,d1传给了in,传参顺序传错了;对于这些运算符的函数重载,如果是双操作数的操作符重载,它是按照操作数的顺序进行传参的(即第一个参数是左操作数,第二个参数是右操作数);

        虽然d1>>cin可以实现,但是d1>>cin并不符合我们的使用习惯,所有这时候就不要将其重载为成员函数;可以将它定义为全局的,但是对于私有成员右访问不了了,这个时候,友元函数就派上用场了(友元函数会破话封装性,一般不建议使用);

        对于返回值还没有处理,刚才只能实现单次的输入输出,如果想要连续的输入和输出,那么返回类型cin和cout类类型(及cout的类型是ostream、cin的类型是istream);

//Date.h
class Date
{
	//友元函数
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);

public:
	//构造函数
	Date(int year = 1, int month = 1, int day = 1);
	/*
     ......
     ......
    */

	//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.c
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;
}

六、const修饰类的成员函数 

请思考一下几个问题:
         1. const对象可以调用非const成员函数吗?
        2. 非const对象可以调用const成员函数吗?
        3. const成员函数内可以调用其它的非const成员函数吗?
        4. 非const成员函数内可以调用其它的const成员函数吗?

通过下面的代码,做出解答 

class Date
{
public:
	void Display()
	{
		cout << "Display ()" << endl;
		cout << "year:" << _year << endl;
		cout << "month:" << _month << endl;
		cout << "day:" << _day << endl << endl;
	}
	void Display() const
	{
		cout << "Display () const" << endl;
		cout << "year:" << _year << endl;
		cout << "month:" << _month << endl;
		cout << "day:" << _day << endl << endl;
	}
private:
	int _year; // 年
	int _month; // 月
	int _day; // 日
};
void Test()
{
	Date d1;
	d1.Display();

	const Date d2;
	d2.Display();
}

为了防止这些问题的发生,常常对成员函数进行const修饰,其本质是对*this的一个修饰;就是在成员函数的后面加上const;

对于非const修饰的对象可以调用const修饰的成员函数,反之不行;

对于非const成员函数内可以调用其它的const成员函数,反之不行;

但是也不是所有的成员函数都需要进行const的修饰,以上面的日期类来说,对于构造函数,是需要我们对其进行初始化的,必然存在值的修改,这种情况就不可以用const修饰;对于比较日期间的大小,并不存在值的改变,为了防止误操作,加上const会更好一些;

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

这两个默认成员函数一般不用重新定义 ,编译器默认会生成。 

class Date
{ 
public :
     Date* operator&()
     {
         return this;
        //return nullptr;不允许获取对象的地址
     }
 
     const Date* operator&()const
     {
         return this;
     }
private :
     int _year ; // 年
     int _month ; // 月
     int _day ; // 日
};
这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比如 想让别人获取到指定的内容

猜你喜欢

转载自blog.csdn.net/sjsjnsjnn/article/details/124539534