CPP对象的初始化清理
构造函数进行初始化
- 构造函数
- 没有返回值 不用写void
- 函数名 与类名相同
- 构造函数可以有参数可以发生重载
- 创建对象会自动调用一次且仅有一次(初始化)
构造函数
初始化会执行1
2
3
4
5
6
7
8
9
10
11
12
13
14class Person
{
public:
Person()
{
cout << "Person" << endl;
}
};cout << "Person" << endl;一次1
2
3
4
5
6
7
8
9
10
11void test01()
{
Person p; //执行完自动调用析构函数
}
int main()
{
test01();
}析构函数
- 会进行清理操作
- 在函数名前加~即可
- 无参数 不重载
- 对象销毁前自动调用且只有一次
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class Person
{
public:
Person()
{
cout << "Person构造函数" << endl;
}
~Person() //析构函数就算不加执行完也会空实现的析构函数创建,构造函数同理
{
cout << "Person析构函数" << endl;
}
};1
2
3
4
5
6
7
8int main()
{
Person p; //执行构造
//test01(); //test函数调用完析构
system("pause");
return 0; //析构函数
}

Invitation
hgez6
666666
created:14/10/2022
Big Bird Luck Card
Be happy .
This is luck card,wish you a nice day .
评论
