0
点赞
收藏
分享

微信扫一扫

C++——构造函数和析构函数

(文章目录)

默认成员函数

1. 构造函数

1. 概念

<font color=blue> 在对象构造时调用的函数,这个函数完成初始化工作</font>

2. 特性

特性1-3

<font color=blue> 1.没有返回值 2.函数名跟类名相同 3.对象实例化时编译器自动调用对应的构造函数 </font>

在这里插入图片描述

特性 4

<font color=blue> 4.构造函数可以重载</font>

在这里插入图片描述

<font color=red> 当使用构造函数不传参数时,若写成date d2(); ,则会报错</font>

特性 5

<font color=blue> 5.如果类中没有显式定义构造函数,则c++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成</font>

  • 内置类型

在这里插入图片描述

<font color=blue> 若输出结果,则会发现为随机值 对于默认生成无参构造函数,</font><font color=red> 针对内置类型的成员变量没有做处理</font>

  • 自定义类型
#include<iostream>
using namespace std;
class Time
{
public:
	Time()
	{
		_hours = 0;
		_minute = 0;
		_seconds = 0;
	}
private:
	int _hours;
	int _minute;
	int _seconds;
};
class date
{
public:
	//没有构造函数,则编译器会自动生成一个无参的默认构造函数
	void print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
	Time _t;//调用自定义类型
};
int main()
{
	date d;//无参数
	d.print();
	return 0;
}

在这里插入图片描述

<font color=blue> 在date类中又定义了一个自定义类型time</font> <font color=red> 对于默认生成无参构造函数,针对自定义类型的成员变量,调用它的构造函数初始化</font>

特性 6

<font color=blue> 6.无参的构造函数和全缺省的构造函数都被称为默认构造函数,并且默认构造函数只能有一个</font>

<font color=red> 构造函数:(不用传参数) 1.自己实现的无参的构造函数 2.自己实现的全缺省构造函数 3.自己没写编译器自动生成的</font>

-<font color=blue> 既想要带参数,又想要不带参数的 如何使用一个构造函数完成?</font> <font color=red> 全缺省 若参数没有传过去,则使用缺省参数 若有参数,则直接进入函数中 </font>

#include<iostream>
using namespace std;
class date
{
public:
	date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	date d;//无参数
	d.print();//1-1-1
	date d2(2022, 12, 20);//带参数
	d2.print();//2022-12-20
	return 0;
}

2. 析构函数

1. 概念

<font color=blue> 对象在销毁时会自动调用析构函数,完成类的一些资源清理工作</font>

2.先构造后析构

#include<iostream>
using namespace std;
class stack
{
public:
	stack(int n=10)//构造函数
	{
		_a = (int*)malloc(sizeof(int) * n);
		_size = 0;
		_capity = n;
	}
	~stack()//析构函数
	{
		free(_a);
		_a = nullptr;
		_size = _capity = 0;
	}

private:
	int* _a;
	int _size;
	int _capity;
};
int main()
{
	stack s1;
	stack s2;
	return 0;
}

<font color=blue> 若使用构造函数malloc开辟一块空间,则使用析构函数free销毁空间</font> 在这里插入图片描述

先通过<font color=red> 构造s1,再构造s2</font> 由于在栈中,满足先进后出,所以<font color=red> 先析构s2,再析构s1 </font>

3. 对于成员变量

#include<iostream>
using namespace std;
class Time
{
public:
	~Time()//析构函数
	{
		cout << "~Time()" << endl;
	}
private:
	int _hours;
	int _minute;
	int _seconds;
};
class date
{
public:
	//没有构造函数,则编译器会自动生成一个无参的默认构造函数
	void print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
	Time _t;//调用自定义类型
};
int main()
{
	date d;//无参数
	d.print();
	return 0;
}

<font color=blue> 对于默认生成无参构造函数,针对自定义类型的成员变量,调用它的析构函数</font>

举报

相关推荐

0 条评论