post on 17 Mar 2025 about 3020words require 11min
CC BY 4.0 (除特别声明或转载文章外)
如果这篇博客帮助到你,可以请我喝一杯咖啡~
参考博客
[C++ 类构造函数 & 析构函数 菜鸟教程](https://www.runoob.com/cplusplus/cpp-constructor-destructor.html)
在 CPP 中,类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。
构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。构造函数可用于为某些成员变量设置初始值。
new
操作符创建的,那么在分配内存后,构造函数会被调用以初始化对象。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class ClassName {
public:
// 默认构造函数
ClassName() {
// 初始化代码
}
// 带参数的构造函数
ClassName(Type1 param1, Type2 param2) {
// 初始化代码,使用参数
}
// 成员初始化列表
ClassName(Type1 param1, Type2 param2) : member1(param1), member2(param2) {
// 其他初始化代码
}
};
类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行,用于清理对象在销毁前需要释放的资源。
析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,也不能带有任何参数。析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。
1
2
3
4
5
6
7
class ClassName {
public:
// 析构函数
~ClassName() {
// 清理代码
}
};
析构函数不能有参数,因为如果析构函数可以有参数,那么在对象销毁时,就必须提供这些参数,这在逻辑上是不合理的,因为对象正在被销毁,无法再提供额外的信息。
成员初始化列表是一种在构造函数体内初始化类成员变量的方式。
1
2
3
4
Line::Line( double len): length(len)
{
cout << "Object is being created, length = " << len << endl;
}
1
2
3
4
5
Line::Line( double len)
{
length = len;
cout << "Object is being created, length = " << len << endl;
}
1
2
3
4
C::C( double a, double b, double c): X(a), Y(b), Z(c)
{
....
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <string>
using namespace std;
class MyComputer
{
public:
~MyComputer();_ // 这是析构函数声明_
MyComputer(string cpu, string gpu, int memory);_ // 这是构造函数声明_
string get_cpu();_ // 获取CPU信息_
string get_gpu();_ // 获取GPU信息_
int get_memory();_ // 获取内存信息_
private:
string cpu;
string gpu;
int memory;
};
_// 成员函数定义,包括构造函数_
MyComputer::MyComputer(string cpu, string gpu, int memory) : cpu(cpu), gpu(gpu), memory(memory)
{
cout << "Computer is being created" << endl;
cout << "CPU: " << cpu << endl;
cout << "GPU: " << gpu << endl;
cout << "Memory: " << memory << "GB" << endl;
}
MyComputer::~MyComputer()
{
cout << "Computer is being destroyed" << endl;
}
string MyComputer::get_cpu()
{
return cpu;
}
string MyComputer::get_gpu()
{
return gpu;
}
int MyComputer::get_memory()
{
return memory;
}
int main()
{
MyComputer computer("Intel 13600kf", "NVIDIA RTX 4060Ti", 16);
cout << "CPU: " << computer.get_cpu() << endl;
cout << "GPU: " << computer.get_gpu() << endl;
cout << "Memory: " << computer.get_memory() << "GB" << endl;
return 0;
}
定义一个类 MyComputer
:
构造函数:
析构函数:
成员函数:
get_cpu()
、get_gpu()
和 get_memory()
函数,用于获取计算机的属性值。主函数 main()
:
MyComputer
对象,传入 CPU、GPU 和内存参数。说白了,构造函数就是对象在创建时执行的函数,析构函数就是在对应删除时执行的函数
对于使用 new 和 delete 关键字构建的动态对应,在执行对应的代码的时候会自动调用对应的构造和析构函数
Related posts