C++入门基础知识140—【关于C++ 类构造函数 & 析构函数】 - 教程

成长路上不孤单

【14后///C++爱好者///持续分享所学///如有需要欢迎收藏转发///】

今日分享关于C++ 类构造函数 & 析构函数的相关内容!

关于【C++ 类构造函数 & 析构函数】

类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。

构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。构造函数可用于为某些成员变量设置初始值。

下面的实例有助于更好地理解构造函数的概念:

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

#include <iostream>

using namespace std;

classLine

{

public:

voidsetLength( doublelen );

doublegetLength( void);

Line(); // 这是构造函数

private:

doublelength;

};

// 成员函数定义,包括构造函数

Line::Line(void)

{

cout << "Object is being created"<< endl;

}

voidLine::setLength( doublelen )

{

length = len;

}

doubleLine::getLength( void)

{

returnlength;

}

// 程序的主函数

intmain( )

{

Line line;

// 设置长度

line.setLength(6.0);

cout << "Length of line : "<< line.getLength() <<endl;

return0;

}

当上面的代码被编译和执行时,它会产生下列结果:

带参数的构造函数

默认的构造函数没有任何参数,但如果要求,构造函数也可以带有参数。这样在创建对象时就会给对象赋初始值,如下面的例子所示:

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

#include <iostream>

using namespace std;

classLine

{

public:

voidsetLength( doublelen );

doublegetLength( void);

Line(doublelen); // 这是构造函数

private:

doublelength;

};

// 成员函数定义,包括构造函数

Line::Line( doublelen)

{

cout << "Object is being created, length = "<< len << endl;

length = len;

}

voidLine::setLength( doublelen )

{

length = len;

}

doubleLine::getLength( void)

{

returnlength;

}

// 程序的主函数

intmain( )

{

Line line(10.0);

// 获取默认设置的长度

cout << "Length of line : "<< line.getLength() <<endl;

// 再次设置长度

line.setLength(6.0);

cout << "Length of line : "<< line.getLength() <<endl;

return0;

当上面的代码被编译和执行时,它会产生下列结果:

使用初始化列表来初始化字段

使用初始化列表来初始化字段:

上面的语法等同于如下语法:

假设有一个类 C,具有多个字段 X、Y、Z 等要求进行初始化,同理地,您可以使用上面的语法,只需要在不同的字段利用逗号进行分隔,如下所示:

类的析构函数

类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。

析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,也不能带有任何参数。析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。

下面的实例有助于更好地理解析构函数的概念:

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

#include <iostream>

using namespace std;

classLine

{

public:

voidsetLength( doublelen );

doublegetLength( void);

Line(); // 这是构造函数声明

~Line(); // 这是析构函数声明

private:

doublelength;

};

// 成员函数定义,包括构造函数

Line::Line(void)

{

cout << "Object is being created"<< endl;

}

Line::~Line(void)

{

cout << "Object is being deleted"<< endl;

}

voidLine::setLength( doublelen )

{

length = len;

}

doubleLine::getLength( void)

{

returnlength;

}

// 程序的主函数

intmain( )

{

Line line;

// 设置长度

line.setLength(6.0);

cout << "Length of line : "<< line.getLength() <<endl;

return0;

}

当上面的代码被编译和执行时,它会产生下列结果:

posted @ 2025-11-04 09:49  yangykaifa  阅读(8)  评论(0)    收藏  举报