类和对象【C++】【中篇】

文章详细介绍了C++中的构造函数、析构函数、拷贝构造函数和赋值重载函数的概念、特征及使用场景,强调了它们在对象生命周期管理和资源管理中的作用。此外,还讨论了赋值运算符重载的注意事项,包括返回值类型和效率问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、类的6个默认成员函数

1、构造函数 

2、析构函数

3、拷贝构造函数 

4、赋值重载函数

二、赋值运算符重载 


一、类的6个默认成员函数

注意:默认成员函数不能在类外面定义成全局函数。因为类里没有的话会自动生成,就会产生冲突。 

1、构造函数 

对于下面这个程序,可以看到,每次创建对象时,我们都需要手动调用Init函数,这样是不是有些麻烦呢?

class Date
{
public:
	void Init(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.Init(2023, 5, 1);
	d1.Print();

    Date d2;
	d2.Init(2023, 5, 2);
	d2.Print();
	return 0;
}

构造函数就可以很好地解决这个问题。

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

其主要任务并不是开空间创建对象,而是初始化对象。

特征:

1、函数名与类名相同。

2、无返回值。(也不需要void)

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

4、构造函数可以重载。

使用举例: 

class Date
{
public:
	//无参构造函数
	Date()
    {}
	//带参构造函数
	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(2023, 5, 8);//调用有参的构造函数
	return 0;
}

注意:

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

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

3、编译器自动生成的默认构造函数,对内置类型不做处理(有些编译器可能会),对自定义类型成员则会调用它的默认构造。

一般情况下,有内置类型时,就需要自己写构造函数,如果全是自定义类型成员,就可以考虑让编译器自己生成。

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

4、无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。注意:无参构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数,都可以认为是默认构造函数。

2、析构函数

(1)概念

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

(2)特性 

1、析构函数名是在类名前加 ~

2、无参数无返回类型

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

4、析构函数不能重载

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

1、一般情况下,有动态申请资源,就需要显示写析构函数释放资源

2、没有动态申请的资源,就不需要写析构

3、如果需要释放的资源的成员类型都是自定义类型,则不需要写析构 

3、拷贝构造函数 

(1)概念

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

(2)特征 

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

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

3、若未显示定义,编译器会生成默认的拷贝构造函数。默认拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝。

class Date
{
public:
	Date(int year=1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	Date(const Date& d)
	{
		//this->_year = d._year;(d2的_year = d1的_year)
		_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;
}

4、赋值重载函数

d1=d2;//d1.operator =(d2);

已经存在的两个对象之间复制拷贝。

注意:与拷贝构造函数不同的是,拷贝构造函数是用一个对象初始化另一个对象

 下面这个关于日期类的赋值重载函数有没有什么问题?

	void operator =(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
int main()
{
	Date d1(2023, 5, 8);//带参构造函数
	Date d2(d1);//拷贝构造函数,用一个已经存在的对象初始化另一个对象
	Date d3(d2);//拷贝构造函数
	//将d2赋值给d1,已经存在的两个对象的拷贝复制
	d1 = d2 = d3;
	return 0;
}

 在赋值时,如果是连续赋值,上面的函数就会有问题。

d1=d2=d3;

d3赋值给了d2后,应该有一个返回值,而我们上面写的函数的返回值是空。

	Date operator =(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
		return *this;//传值返回,返回的是对象的拷贝,不好
	}

如果像上面这样写,是传值返回,就需要再调用拷贝构造函数

因此,为了提高效率,我们可以将返回值改为引用。

	Date& operator =(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
		return *this;//因为出了作用域*this还在,所以可以用引用返回。
	}

上面的代码对于d1=d1;这样的代码是可以编译通过的,如果不想,可以按照如下写法:

	Date& operator =(const Date& d)
	{
        if(*this != &d)
        {
            _year = d._year;
		    _month = d._month;
		    _day = d._day;
        } 
		return *this;//因为出了作用域*this还在,所以可以用引用返回。
	}

默认生成的赋值重载函数跟拷贝构造一样:

1、内置类型成员:值拷贝/浅拷贝。

2、自定义类型成员会去调用它的赋值重载函数。 

二、赋值运算符重载 

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

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

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

注意:

(1)不能通过其他连接符号来创建新的操作符。

(2)重载操作符必须有一个类类型参数。

(3)用于内置类型的运算符,其含义不能改变,如+

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

(5)(.*)(::)(sizeof)(?:)(.)注意以上5个运算符不能重载,笔试选择题中经常出现。

class Date
{
public:
	void Init(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
	//bool operator == (Date* this,const Date& d2)
	bool operator ==(const Date& d2)
	{
		return _year == d2._year && _month == d2._month && _day == d2._day;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1, d2;
	d1.Init(2023, 5, 1);
	d2.Init(2023, 5, 2);
	if (d1 == d2)
	{
		printf("相等");
	}
	else
	{
		printf("不相等");
	}
	return 0;
}

三、日期类的实现 

#include <iostream>
#include <functional>
#include<cassert>
using namespace std;
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);//带参构造函数
	//如果这样写:
	//1、Date d1(2023, 5, 1);
	//2、const Date d2(2004, 3, 5);
	//d1.Print(Date* this);//可以
	//不可以,因为从const Date*this到Date *this权限放大了
	//d2.Print(Date* this);
	//void Print()
	//{
	//	cout << _year << "-" << _month << "-" << _day << endl;
	//}
	//如果将Print的参数改成const Date *this
	//对于1来说是权限缩小,对于2来说是平移,都是允许的
	//只要不改变对象成员变量的函数都应该const,这样const对象和普通对象就都可以调用了

	void Print()const
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
	bool operator <(const Date& x);
	bool operator >(const Date& x);
	bool operator ==(const Date& x);
	bool operator <= (const Date& x);
	bool operator >= (const Date& x);
	bool operator !=(const Date& x);
	int GetMonthDay(int year, int month);
	Date& operator += (int day);
	Date operator + (int day);
	Date& operator++();
	Date operator++(int);//后置++
	Date& operator -= (int day);
	Date& operator - (int day);
	Date& operator--();
	Date operator--(int);//后置++
	int operator-(const Date& x);
private:
	int _year;
	int _month;
	int _day;
};
#include"Date.h"
Date::Date(int year, int month, int day)//带参构造函数
{
	if (year > 0 && month > 0 && month < 13 && day>0 && day <= GetMonthDay(year, month))
	{
		_year = year;
		_month = month;
		_day = day;
	}
	else
	{
		cout << "日期非法" << endl;
		assert(false);
	}
}
bool Date::operator <(const Date& x)
{
	if (_year < x._year)return true;
	else if (_year == x._year && _month < x._month)return true;
	else if (_year == x._year && _month == x._month && _day < x._day)return true;
	else return false;
}
bool Date :: operator ==(const Date& x)
{
	return _year == x._year && _month == x._month && _day == x._day;
}
bool Date:: operator <= (const Date& x)
{
	return *this < x || *this == x;
}
bool Date :: operator >(const Date& x)
{
	return !(*this <= x);
}
bool Date :: operator >= (const Date& x)
{
	return *this > x || *this == x;
}
bool Date :: operator!=(const Date& x)
{
	return !(*this == x);
}

int Date::GetMonthDay(int year, int month)
{
	int daysArr[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;
	}
	return daysArr[month];
}
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)
{
	Date tmp(*this);
	tmp += day;
	return tmp;
}
Date& Date :: operator++()//前置++
{
	*this += 1;
	return *this;
}
Date Date::operator++(int)//后置++
{
	Date tmp(*this);
	*this += 1;
	return tmp;
}
Date& Date :: operator -= (int day)
{
	if (_day < 0)
	{
		return *this += -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;
}

Date& Date:: operator--()
{
	*this -= 1;
	return *this;
}
Date Date:: operator--(int)//后置++
{
	Date tmp(*this);
	*this -= 1;
	return tmp;
}
int Date:: operator-(const Date& x)
{
	Date max = *this;
	Date min = x;
	int flag = 1;
	if (*this<x)
	{
		max = x;
		min = *this;
		flag = -1;
	}
	int n = 0;
	while (min != max)
	{
		++min;
		++n;
	}
	return n * flag;
}
//void Date:: operator <<(ostream& out)
//{
//	out << _year << "年" << _month << "月" << _day << "日" << endl;
//}

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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值