C++类与对象(核心)

发布于:2022-11-14 ⋅ 阅读:(485) ⋅ 点赞:(0)

C++类与对象(核心)

1.类的默认成员函数

1.1 六个默认成员函数

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

请添加图片描述

1.构造函数:初始化

2.析构函数:清理

3.拷贝构造:同类对象初始化

4.赋值重载:对象赋值对象

5.非const对象取地址:可读可写内容

6.const对象取地址:可读不可写内容


2.构造函数

2.1 构造函数概念

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

总结:

  1. 名字与类型相同
  2. 编译器自动调用
  3. 确保成员初始化
  4. 对象生命周期只调用一次

构造函数产生原因:对于Date类,可以通过SetDate公有的方法给对象设置内容,但是如果每次创建对象都调用该方法设置信息,太麻烦了,基于此就出现了构造函数用于初始化对象!

class Date
{ 
public:
    Date(){}//默认构造函数,不写自动生成
 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.SetDate(2022,5,1);
 	d1.Display();
   
    Date d2;
 	d2.SetDate(2018,7,1);
 	d2.Display();
 	return 0;
}

2.2 构造函数特性

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

补充:C++中把类型分为了内置类型和自定义类型

  • 内置类型:int/char/float/double/指针…

  • 自定义类型:class/struct定义的类型

  • 默认生成的构造函数对于内置类型成员变量不处理,对于自定义类型成员变量才处理

  • 内置类型的成员会完成值拷贝(即浅拷贝)

  • 自定义类型的成员会调用这个成员的拷贝构造

image-20220713141712819

也就是说内置类型不处理,值为随机值;自定义类型处理,值为调用默认构造函数的结果

构造函数特性:

1.函数名与类名相同

2.无返回值

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

4.构造函数可以重载

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

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

7.注意:无参构造函数全缺省构造函数、我们没写编译器默认生成的构造函数,都可以认为是默认构造函数

class Date
{ 
public:
 //0.不写构造函数,编译器自动生成一个构造函数
 Date(){}//自动生成

 // 1.无参构造函数
 Date (){}
 
 // 2.带参构造函数
 Date (int year,int month,int day )
 {
	 _year = year;
 	_month = month;
 	_day = day;
 }
    
private:
 		int _year;
 		int _month;
 		int _day;
    
    	//以下代码为C++11补丁,针对编译器自己生成默认成员函数不初始化问题
    	//int _year=0;
    	//int _month=0;
    	//int _day=0;
};

void TestDate()
{
     // 注意:如果通过无参构造函数创建对象时,对象后面不用跟括号,否则就成了函数声明
     Date d1;// 调用无参构造函数
     Date d2 (2015, 1, 1);// 调用带参的构造函数
     Date d3();//声明了d3函数,该函数无参,返回一个日期类型的对象
}

3.析构函数

3.1 析构函数概念

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


3.2 析构函数特性

1.析构函数名是在类名前加上字符 ~

2.无参数

3.无返回值

4.一个类有且只有一个析构函数,若未显示定义,则系统自动生成默认的析构函数

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

typedef int DataType;
class SeqList
{ 
public:
 SeqList (int capacity = 10)//全缺省构造函数---初始化类的成员变量
 {
 	_Data = (DataType*)malloc(capacity * sizeof(DataType));
 	assert(_Data);
 	_size = 0;
 	_capacity = capacity;
 }
 
 ~SeqList()//析构函数---销毁类的成员
 {
 	if(_Data)
 	{
 		free(_Data); // 释放堆上的空间
 		_pData = NULL; // 将指针置为空
 	    _capacity = 0;
 		_size = 0;
 	}
 }
 
private:
 		int* _Data ;
 		size_t _size;
 		size_t _capacity;
};

4.拷贝构造函数

4.1 拷贝构造函数概念

拷贝构造函数:只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时由编译器自动调用

使用拷贝构造函数三种情况:

1.对象初始化对象

2.函数参数以对象传递

3.函数的返回值以对象返回

简言之:初始化对象、返回值对象、参数对象

使用拷贝构造函数的结论:一般的类,自己生成拷贝构造就够用了。只有像stack这样的类,自己直接管理资源,需要自己实现深拷贝

补充:在传值传参和传值返回的过程中,只要是在一个表达式调用的连续步骤(一般是return的时候)中,就可能产生优化

拷贝构造没有优化的编译器:返回值赋值给临时变量(中间对象),临时变量(中间对象)在赋值给对象,经历两次拷贝构造

请添加图片描述

class Weight
{
public:
    Weight()
    {
        cout<<"Weight()"<<endl;
    }
    weight(const Weight& w)
    {
        cout<<"Weight(const Weight& w)"<<endl;
    }
    void f()
    {}
};

Weight func1(Weight u)//调用函数传参时会拷贝构造一次---函数参数以对象传递
{
    Weight v(u);//Weight v(u)和Weight v=u 等价  拷贝构造一次---对象初始化
    Weight w=v;//拷贝构造一次---对象初始化
    return w;//拷贝构造一(或二)次---函数返回值以对象返回   先拷贝构造一个临时变量,再拷贝给赋的值

    //一个表达式中,连续步骤的构造+拷贝构造或者拷贝构造+拷贝构造,编译器可能优化,合二为一
}
//func1调用4次拷贝构造

Weight func2(Weight& u)//这里用的是别名,不会调用拷贝构造
{
    Weight v(u);//拷贝构造一次
    Weight w=v;//拷贝构造一次
    return w;//拷贝构造一次
}
//func2调用3次拷贝构造

Weight& func3(Weight& u)//这里用的别名,不拷贝构造
{
    Weight v(u);//拷贝构造一次   直接构造
    Weight w=v;//拷贝构造一次	   隐式类型转换
    return w;//返回值用的别名,不拷贝构造
}
//func3调用2次拷贝构造

拷贝构造优化的编译器:把中间对象优化掉,直接用第一个对象拷贝构造第三个对象

image-20220920163233306

//例题:这个函数调用了几次拷贝构造函数?    答案:7次
Weight f(Weight u)
{
	Weight v(u);
	Weight w=v;
	return w;
}
int main()
{
	Weight x;
	Weight y=f(f(x));
}

image-20220715180912775


4.2 拷贝构造函数特性

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

2.拷贝构造函数的参数只有一个且必须使用引用传参,使用传值方式会引发无穷递归调用

3.若未显示定义,系统生成默认的拷贝构造函数。默认的拷贝构造函数对象按“字节序”完成拷贝,这种拷贝我们叫做浅拷贝,或者值拷贝

注:字节序是指多字节数据在计算机内存中存储或者网络传输时各字节的存储顺序

举例:

class Date
{
public:
 Date(int year = 2022, int month = 5, int day = 1)//全缺省构造函数
 {
 	_year = year;
 	_month = month;
	_day = day;
 }
 
 Date(const Date& d)//拷贝构造函数
 {
 	_year = d._year;
 	_month = d._month;
 	_day = d._day;
 }
 
private:
 	int _year;
 	int _month;
 	int _day;
};

int main()
{
 	Date d1;
 	Date d2(d1);
 	return 0;
}
class Date
{
public:
 Date(int year = 2022, int month = 5, int day = 1)//全缺省构造函数
 {
	 _year = year;
 	_month = month;
 	_day = day;
 }
 //生成默认拷贝构造函数
    //Date(const Date& d){}
    
private:
 	int _year;
 	int _month;
 	int _day;
};

int main()
{
	Date d1;//调用无参构造函数,使用全缺省构造函数
 	// 这里d2调用的默认拷贝构造完成拷贝,d2和d1的值也是一样的。
 	Date d2(d1);
 	return 0;
}

4.3 拷贝构造函数的浅拷贝问题

一:传值引发的无穷递归调用

传值进去生成一个临时拷贝对象,临时拷贝对象又是值,又生成一个临时拷贝对象…循环往复

image-20220713145336884

二:const引发的浅拷贝崩溃

class String
{
public:
 String(const char* str = "jack")
 {
 	_str = (char*)malloc(strlen(str) + 1);
 	strcpy(_str, str);
 }
    
 ~String()
 {
 	cout << "~String()" << endl;
 	free(_str);
 }
    
private:
 	char* _str;
};

int main()
{
 	String s1("hello");
 	String s2(s1);//这里程序会崩掉 需要深拷贝才能解决问题
}

5.运算符重载

5.1 运算符重载概念

C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似

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

函数原型:返回值类型 operator操作符(参数列表) bool operator >(const Date &d1)


5.2 运算符重载性质

运算符重载规则:

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

2.重载操作符必须有一个类类型或者枚举类型的操作数

3.用于内置类型的操作符,其含义不能改变,例如:内置的整型+,不能改变其含义

4.作为类成员的重载函数时,其形参看起来比操作数数目少1,operator成员函数的操作符有一个默认的形参this,限定为第一个形参

5. .* :: sizeof ?: . 注意以上5个运算符不能重载

总结:

  1. 内置类型,可以直接用各种运算符
  2. 自定义类型,不能直接使用各种运算符
  3. 为了让自定义类型可以使用各种运算符,制定了运算符重载规则
  4. 全局运算符重载:operator==(d1,d2);
  5. 成员运算符重载:d1.operator==(d2);
// 全局的operator==
class Date
{ 
public:
 Date(int year = 2022, int month = 5, 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;
 }
};

if(operator==(d1,d2))//类外的operator,全局operator
{
    cout<<"=="<<endl;
}

if(d1.operator==(d2))//类里面的operator,成员operator
{
    cout<<"=="<<endl;
}

if(d1==d2)//编译器会处理成对应重载运算符调用if(operator==(d1,d2)){}或if(d1.operator(d2)){}
{
    cout<<"=="<<endl;
}

void Test ()
{
 	Date d1(2022, 5, 1);
 	Date d2(2022, 6, 1);
 	cout<<(d1 == d2)<<endl;
}
class Date
{ 
public:
 Date(int year = 2022, int month = 5, int day = 1)
 {
 	_year = year;
 	_month = month;
 	_day = day;
 }
 
 // bool operator==(Date* this, const Date& d2)
 // 这里需要注意的是,左操作数是this指向的调用函数的对象
    
 bool operator==(const Date& d2)//操作符重载 隐含Date* this指针
 {
  	return _year == d2._year;
 	&& _month == d2._month;
 	&& _day == d2._day;
 }
private:
 	int _year;
 	int _month;
	int _day;
};

void Test ()
{
 	Date d1(2022, 5, 1);
 	Date d2(2022, 6, 1);
 	cout<<(d1 == d2)<<endl;//d1==d2 ->d1.operator==(const Date& d2);
}

5.3 赋值运算符重载特性

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

 Date& operator=(const Date& d)//返回Date类的引用
 {
 	if(this != &d)//判断是否自己赋值自己
 	{
		_year = d._year;
 		_month = d._month;
 		_day = d._day;
     }
     return *this;
 }
 
private:
 		int _year ;
 		int _month ;
 		int _day ;
};
void Test ()
{
 	Date d1(2022, 5, 1);
    Date d2(2022, 10,1);
 	Date d3(d1);//拷贝构造---一个存在的对象去初始化另一个要创建的对象
    d2=d1;//赋值重载/复制拷贝---两个已经存在的对象之间赋值
    d1(d2);//赋值重载---两个已经存在的对象赋值
}

赋值运算符特性:

1.注意参数至少有一个且用引用传参

2.有返回值—为了支持连续赋值:i=j=k

3.要检测是否自己给自己赋值

4.返回值:返回*this

5.一个类如果没有显式定义赋值运算符重载(operator=),编译器也会生成一个,完成对象按字节序的值拷贝

拷贝构造与赋值重载的区分:

  1. 拷贝构造:一个存在的对象去初始化另一个要创建的对象
  2. 赋值重载:两个已经存在的对象之间赋值

6.const成员函数

6.1 const修饰类的成员函数

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

1.void Display(const Date* this)//这里const修饰thiis指针

2.void Display(const Date* this)const;//内部的const修饰this指针外部的const修饰Date* const this

3.由于this是隐含的,所以不能再参数里面加const,C++将const加在参数列表后面,实现给隐含的this加const

image-20220713153813194

1.非const类型:可读可写

2.cosnt类型:可读不可写

3.建议成员函数不修改成员变量的成员函数,都可以加上const,普通对象和const对象都可以调用

请添加图片描述

由代码思考问题:

  1. const对象可以调用非const成员函数吗?—不能,权限放大
  2. 非const对象可以调用const成员函数吗?—可以,权限缩小
  3. const成员函数内可以调用其它的非const成员函数吗?—不能,权限放大
  4. 非const成员函数内可以调用其它的const成员函数吗?—可以,权限缩小

6.2 取地址及 const 取地址运算符重载

class Date
{ 
public :
 Date* operator&()//普通对象取地址
 {
 	return this;
 }
 
 const Date* operator&()const//const取地址
 {
 	return this;
 }
    
private:
 		int _year ; // 年
 		int _month ; // 月
 		int _day ; // 日
};
void func(Date& d)
{
    cout<<&d<<endl;
}
void func2(const Date& d1)//p
{
    cout<<&d1<<endl;
}

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


7.日期类的实现

7.1 日期类的代码

//Date.h
#pragma once
#include <iostream>
#include <assert.h>
using std::cin;
using std::cout;
using std::endl;

class Date
{
public: 
	bool isLeapYear(int year)//是闰年     4年一润且百年不润,400年一润
	{
		return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
	}

	int GetMonthDay(int year, int month);

	// 默认生成的析构函数,内置类型成员不做处理,自定义类型成员会去调用它的析构函数
	Date(int year = 1, int month = 1, int day = 1);

	//Date(const Date& d)
	//{
	//	_year = d._year;
	//	_month = d._month;
	//	_day = d._day;
	//}

	//Date& operator=(const Date& d)
	//{
	//	if (this != &d)
	//	{
	//		_year = d._year;
	//		_month = d._month;
	//		_day = d._day;
	//	}

	//	return *this;
	//}

	void Print() const
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

	Date operator+(int day)  const;
	Date& operator+=(int day);

	Date operator-(int day)  const;
	Date& operator-=(int day);

    //代码短的用inline
	// ++d1
	Date& operator++()      // 前置
	{
		*this += 1;
		return *this;
	}

	// d1++
	Date operator++(int) // 后置 这里的int传的值大小无关,只是用于区分,一般写0或1
	{
		Date tmp(*this);//拷贝一份当前值
		*this += 1;
		return tmp;
	}

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

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

	// d1 - d2
	int operator-(const Date& d) const;

	bool operator==(const Date& d)  const;
	bool operator<(const Date& d)  const;

	// inline不支持声明和定义分别放到.h 和.cpp
	// 所以成员函数中要成为inline最好直接在类里面定义
	// 类里面定义默认就是inline
	bool operator>(const Date& d)  const
	{
		return !(*this <= d);
	}

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

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

	// d1 <= d2
	bool operator<=(const Date& d)  const
	{
		return *this < d || *this == d;
	}

private:
	int _year;
	int _month;
	int _day;
};
//Date.cpp
#include "Date.h"

bool Date::operator<(const Date& d)const
{
	if ((_year < d._year)
		|| (_year == d._year && _month < d._month)
		|| (_year == d._year && _month == d._month && d._day < d._day))
	{
		return true;
	}
	else
	{
		return false;
	}
}

// d1 == d2
bool Date::operator==(const Date& d)const
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

int Date::GetMonthDay(int year, int month)
{
	assert(year >= 0 && month > 0 && month < 13);

	const static int monthDayArray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	if (month == 2 && isLeapYear(year))
	{
		return 29;
	}
	else
	{
		return monthDayArray[month];
	}
}

Date::Date(int year, int month, int day)
{
	if (year >= 1 &&
		month <= 12 && month >= 1 &&
		day >= 1 && day <= GetMonthDay(year, month))
	{
		_year = year;
		_month = month;
		_day = day;
	}
	else
	{
		cout << "日期错误" << endl;
	}
}

// d1 + 100 -->d1.operator+(day);

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


Date Date::operator+(int day)
{
	Date ret(*this);

	ret._day += day;
	while (ret._day > GetMonthDay(ret._year, ret._month))
	{
		ret._day -= GetMonthDay(ret._year, ret._month);
		ret._month++;
		if (ret._month == 13)
		{
			++ret._year;
			ret._month = 1;
		}
	}

	return ret;
}

Date Date::operator+(int day)const
{
	Date ret(*this);
	ret += day;

	return ret;
}

// d1 += 100
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 ret = *this;
	ret -= day;
	return ret;
}

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

// d1 - d2 -->  d1.operator-(const Date& d) const 

//最简日期类相减运算
int Date::operator-(const Date& d)const
{
	int flag = 1;//设置标识:1为正数,-1为负数
	Date max = *this;
	Date min = d;
	if (*this < d)
	{
		min = *this;
		max = d;
		flag = -1;
	}

	int n = 0;//天数标识
    //最大值和最小值不相等则让天数+1,用n标记数,最终由n*flag确定相差的天数
	while (min != max)
	{
		++n;
		++min;
	}
	return n * flag;
}
//Test.cpp
#include "Date.h"

void TestDate1()
{
	Date d1(2022, 5, 18);
	Date d2(2023, 3, 20);
	Date d3(2023, 3, 20);

	cout << (d1 < d2) << endl;
	cout << (d1 > d2) << endl;
	cout << (d1 == d3) << endl;
	cout << (d2 <= d3) << endl;
	cout << (d2 == d3) << endl;
}

void TestDate2()
{
	Date d1(2022, 5, 18);
	Date d2 = d1 + 15;
	Date d3;
	d3 = d1 + 15;//dia

	//Date d3 = d1; //调用拷贝构造 Date d3(d1);
	//d1 = d2;	//调用赋值  

	d2.Print();
	d1.Print();

	d1 += 15;
	d1.Print();
}

void TestDate3()
{
	Date d1(2022, 5, 18);
	Date d2 = d1 - 30;
	d2.Print();
	d1 -= 30;
	d1.Print();

	Date d3(2022, 5, 18);
	d3 += 10000;
	d3.Print();

	d3 -= 10000;
	d3.Print();
}


void TestDate4()
{
	Date d1(2022, 5, 18);
	d1 -= -100;
	d1.Print();

	d1 += -100;
	d1.Print();

	Date d2(2022, 5, 18);
	Date ret1 = ++d2; // d2.operator++()
	ret1.Print();
	d2.Print();

	Date ret2 = d2++; // d2.operator++(0)
	ret2.Print();
	d2.Print();
}

void TestDate5()
{
	Date d1(2022, 5, 18);
	Date d2(2020, 2, 4);
	cout << (d1 - d2) << endl;
	cout << (d2 - d1) << endl;
}

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


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

void Func(const Date& d)
{
	d.Print(); // d1.Print(&d); -> const Date*
}

void TestDate6()
{
	Date d1(2022, 5, 18);
	d1.Print(); // d1.Print(&d1); -> Date* 
	Func(d1);
}

int main()
{
	TestDate1();

	return 0;
}
本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到