“析构函数”与“拷贝构造函数”

“析构函数”

1.概念:

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

2.特性:

析构函数是特殊的成员函数。
(1)析构函数名是在类名前加上字符~
(2)无参无返回值
(3)一个类有且只有一个析构函数。若未显示定义,系统会自动生成默认的析构函数

typedef int DataType; class SeqList
{
public:
	SeqList(int capacity = 10)
	{
		_pData = (DataType*)malloc(capacity * sizeof(DataType));
		assert(_pData);
		_size = 0;
		_capacity = capacity;
	}

	~SeqList()
	{
		if (_pData)
		{
			free(_pData);   // 释放堆上的空间
			_pData = NULL;   // 将指针置为空
			_capacity = 0;
			_size = 0;        
		}
	}
private :
	int* _pData ;
	size_t _size;
	size_t _capacity;
};

(4)关于编译器自动生成的析构函数,是否会完成一些事情呢?下面的程序我们会看到,编译器生成的 默认析构函数,对会自定类型成员调用它的析构函数。

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

class Person
{ 
private:
	String _name;
	int    _age;
};

int main()
{
	Person p;
	return 0;
}

“拷贝构造函数”

概念

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

特征

拷贝构造函数也是特殊的成员函数,其特征去下:
(1)拷贝构造函数是构造函数的一个重载形式。
(2)拷贝构造函数的参数只有一个且必须引用传参,使用传值方式会引发无穷递归调用


class Date
{
public:
	Date(int year = 1999, int month = 8, int day = 2)
	{
		_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;
}

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



class Date
{
public:
	Date(int year = 1999, int month = 8, int day = 2)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	

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

int main()
{
	Date d1;
	//这里d2调用的默认拷贝构造完成拷贝,d2和d1的值也是一样的
	Date d2(d1);

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值