类与对象(中)

六大默认成员函数

天选之子:这六个这些函数,编译器会默认生成一个函数,如果我们实现了,编译器就不会生成。
在这里插入图片描述

默认生成的构造与析构函数:
内置类型不做处理(C++11后可以给缺省值)
自定义类型调用对应的构造与析构函数
++++++++++++++++++++++++++++++++++++
默认生成的拷贝构造与赋值重载
内置类型按照值拷贝 按字节进行拷贝
自定义类型成员,调用成员的拷贝构造或者赋值重载

构造函数

特征:

  1. 函数名与类名相同。
  2. 无返回值(可以什么都不用写)(不是要写void,而是什么都没有)。
  3. 对象实例化时编译器自动调用对应的构造函数。
  4. 构造函数可以重载,一个类可以有多个构造函数多种初始化方式。建议提供全缺省的构造函数。
class Date
{
public:
    // 1.无参构造函数
    Date()//无返回值,不需要写void等
    {}
    // 2.带参构造函数
    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(2024,3,29);//调用有参构造函数
    return 0;
}

  1. 如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成。
class Date
{
public:
	void Print()
	{
		cout << _year << "年" << _month << "月" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1;//自动生成的是可以使用的
	d1.Print();
	return 0;
}

在这里插入图片描述
一旦我们自己定义之后,编译器不会自动生成,如果此时存在不符合的构造函数程序会崩溃

class Date
{
public:
	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();
	return 0;
}

在这里插入图片描述
其实看到这里我们会有一个疑惑,为甚么默认生成的构造函数出现的是随机值

因为生成的默认构造函数有缺陷,因为默认的构造函数对于内置类型的成员不做处理自定义类型成员会去调用他的默认构造(不用传参数的构造)。
无参的构造函数和全缺省的构造函数都称为默认构造函数并且默认构造函数只能有一个。
注意:无参构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数,都可以认为是默认构造函数

但是之后在C++11中针对内置类型成员不初始化的缺陷,又打了补丁,即:内置类型成员变量在类中声明时可以给缺省值。

private:
    int _year = 1;
    int _month = 1;
    int _day = 1;

析构函数

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

特征:

  1. 析构函数名是在类名前加上字符 ~。
  2. 无参数无返回值类型。
  3. 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。注意:析构函数不能重载(同构造,内置成员不处理,自定义类型成员会调用他的析构函数)
  4. 对象生命周期结束时,C++编译系统系统自动调用析构函数
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;
}

在这里插入图片描述
如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,比如
Date类;有资源申请时,一定要写,否则会造成资源泄漏,

拷贝构造

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

要注意使用引用,因为传值传参会导致无穷递归
因为传值传参,内置类型,编译器可以直接拷贝(浅拷贝), 自定义类型的拷贝,需要调用拷贝构造
而传引用的话就相当于对这一块空间起别名

class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }
    Date(const Date& d)   // 正确写法。通常拷贝构造的传引用参数都加const 防止有人写反
    //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;
}

在这里插入图片描述
会形成无穷递归的原因是:传值传参,自定义类型需要使用拷贝构造,而拷贝构造是需要传值传参,传值传参又需要拷贝构造。
即因为需要拷贝这个值,所以传值,但是传值就需要调用拷贝,因为拷贝值所以传值,传值又要调拷贝。
在这里插入图片描述
其实我觉得就像是,传值传参调用拷贝构造,拷贝构造需要传值传参两个步骤嵌套住了,开始死循环了。

深浅拷贝

我们知道天选之子的最大好处是不需要写,编译器会自动生成。但是在编译器默认生成的拷贝构造是值拷贝,即以字节为单位进行传参。
值拷贝的问题是:假如 1的指针指向一块空间,你传值传参导致2的指针指向1指针指向的空间,析构时,1指向的空间析构之后,2指针又把同一块空间又析构了一遍。
那么这样传参,指针指向的空间会相互影响。即两个指针指向的空间相同。
在这里插入图片描述

两个指针指向同一块空间问题插入数据相互影响、析构两次程序崩溃
在这里插入图片描述
深拷贝就是开辟另一块空间,可以让他把数据放到另一块空间中
在这里插入图片描述

Stack(const Stack& st)
	{
		_array = (DataType*)malloc(sizeof(DataType) * st._capacity);//开辟一块新的空间
		if (nullptr == _array)
		{
			perror("malloc申请空间失败");
			exit(-1);
		}
		memcpy(_array, st._array, sizeof(DataType) * st._size);//把内容拷贝过去
		_size = st._size;
		_capacity = st._capacity;
	}


什么情况下需要写拷贝构造?
自己实现了析构函数释放空间,就需要写拷贝构造。
因为写析构函数释放了资源,所以我们的函数申请资源了,所以需要拷贝构造
如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请时,则拷贝构造函数是一定要写的,否则就是浅拷贝
为了提高程序效率,一般对象传参时,尽量使用引用类型,返回时根据实际场景,能用引用尽量使用引用。

运算符重载

函数重载是运算符重载的一部分。
C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数。
函数名字为:关键字operator后面接需要重载的运算符符号。
函数原型:返回值类型 operator操作符(参数列表)

//<返回值类型> operator<重载运算符>(参数列表)//默认传单个参数,因为this指针会占据一个名额
 //举例
 bool operator==(const Date& d)
 {
 	//...函数主体	
 }

注意:
1.不能通过连接其他符号来创建新的操作符:比如operator@,不能自创
2.重载操作符必须有一个类类型参数
3.用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义
4.作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
5. .* (点星。没用过) :: (域作用符) sizeof (字节大小) ?:(三目运算) .(成员访问) 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。

赋值运算符重载格式
参数类型:const T&,传递引用可以提高传参效率
返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值
检测是否自己给自己赋值
返回*this :要复合连续赋值的含义

//赋值重载
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;
};
int main()
{
    Date d1(2024, 3, 30);
    Date d2(2024, 4, 20);
    return 0;
}

赋值运算符只能重载成类的成员函数不能重载成全局函数

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 =”必须是非静态成员

原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。
在这里插入图片描述
用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝
注意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值
如果类中未涉及到资源管理,赋值运算符是否实现都可以;一旦涉及到资源管理则必须要实现。

赋值重载是两个已经定义好的对象

Date d1(2024,3,31);
d2=d1;//调用赋值重载
Date d3=d1;//调用拷贝运算

前后置++的区别

//++d
Date& operator++();
//d++
Date operator++(int);
 // 前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载
 // C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递
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;
 }
 // 后置++
 // 注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存一份,然后给this+1
 //  而temp是临时对象,因此只能以值的方式返回,不能返回引用
 Date operator++(int)
 {
 Date temp(*this);
 _day += 1;
 return temp;
 }
private:
 int _year;
 int _month;
 int _day;
};

整个运算符重载的代码安置:
用日期类作为模板

#include"Date.h"
//声明与定义分离
int Date::GetMonthDay(int year, int month)
{
	assert(month > 0 && month < 13);
	int montharr[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400) == 0))
	{
		return 29;
	}
	else
	{
		return montharr[month];
	}
}
Date::Date(int year, int month, int day)
{
    if (month > 0 && month < 13
        && (day > 0 && day <= GetMonthDay(year, month)))
    {
        _year = year;
        _month = month;
        _day = day;
    }
    else
    {
        cout << "日期非法" << endl;
    }
}
//d1.operator==(d2)
bool Date::operator==(const Date& d)
{
    return _year == d._year
        && _month == d._month
        && _day == d._day;
}
bool Date::operator<(const Date& d)
{
    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)//复用
{
    return *this < d || *this == d;
}
bool Date::operator>(const Date& d)
{
    return !(*this <= d);
}
bool Date::operator>=(const Date& d)
{
    return !(*this < d);
}
bool Date::operator!=(const Date& d)
{
    return !(*this == d);
}
//返回值是为了支持连续赋值,保证运算符的特性
Date& Date::operator=(const Date& d)//出作用域存在使用传引用
{
    if (this != &d)//防止自我赋值
    {
        _year = d._year;
        _month = d._month;
        _day = d._day;
    }
    return *this;
}

void Date::Print()
{
    cout << _year << "年" << _month << "月" << _day << endl;
}

Date& Date::operator+=(int day)
{
    if (day < 0)
    {
        *this -= -day;
        return *this;
    }
    _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)
{
    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;
        }
    }*/
    ret += day;//直接复用
    return ret;
}
Date& Date::operator-=(int day)
{
    if (day < 0)
    {
        *this += -day;
        return *this;
    }
    _day -= day;
    while (_day <= 0)//记得day是不能为0的
    {
        _month--;
        if (_month <= 0)
        {
            _year--;
            _month = 12;
        }
        _day += GetMonthDay(_year, _month);
    }
    return *this;
}
Date Date::operator-(int day)
{
    Date ret = *this;
    ret -= day;
    return ret;
}
//前置++
Date& Date::operator++()
{
    *this += 1;
    return *this;
}
//后置++
Date Date::operator++(int)//
{
    Date ret = *this;
    *this += 1;
    return ret;
}
//前置--
Date& Date::operator--()
{
    *this -= 1;
    return *this;
}
//后置--
Date  Date::operator--(int)
{
    Date ret = *this;
    *this -= 1;
    return ret;
}
//-的函数重载,d1-d2
int Date::operator-(const Date& d)
{
    Date max = *this;
    Date min = d;
    int flat = 1;
    if (*this < d)
    {
        max = d;
        min = *this;
        flat = -1;
    }
    int n = 0;
    while (min != max)
    {
        ++min;
        ++n;
    }
    return n * flat;
}

const修饰函数成员

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

class L
{
public:
	void Print()
	{
		cout << _a << endl;
	}

private:
	int _a = 10;

};
void Func(const L& a)
{
	a.Print();
}
int main()
{
	L d;
	Func(d);
	return 0;
}

在这里插入图片描述

在这里插入图片描述
所以我们加上 const,避免权限的放大
const 修饰 *this
this的类型为const L*

	void Print() const//把参数改为 const L*
	{
		cout << _a << endl;
	}

内部不改变成员变量的成员函数时,最好加上const,因为const对象和普通对象都可调用

class Arr
{
public:
	int& operator[](int& d)
	{
		assert(d < 10);
		return _a[d];
	}
	const int& operator[](int& d) const//前面的const修饰返回值是传引用的const
	{								   //后面的const修饰参数类型为const int*
		assert(d < 10);				   //因为参数类型不同从而构成函数重载
		return _a[d];
	}
private:
	int _a[10];
	int _size;
};

int main()
{
	return 0;
}

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

这两个默认成员函数一般不用重新定义 ,编译器默认会生成 所以一般不会去重载取地址

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

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

L* operator&()
{	
	//return *this;
	return (L*)100000;//搞怪玩
}
  • 11
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青青丘比特

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值