C++浅析构造函数的特性
2026/5/22 9:18:37 网站建设 项目流程

构造函数的概念

构造函数是一个特殊的成员函数,名字与类名相同,创建类类型对象时由编译器自动调用,保证每个数据成员都有一个合适的初始值,并且在对象的生命周期内只调用一次。

构造函数的特性

(1)函数名与类名相同。

(2)无返回值。

(3)编译器自动调用对应的构造函数。

(4)构造函数可以重载。

我们这里直接举一个例子

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

#include<iostream>

usingnamespacestd;

classData

{

public:

Data()

{

cout <<"Date()"<<this<< endl;

}

voidInitData(intyear = 1,intmonth = 1,intday = 1)

{

_year = year;

_month = month;

_day = day;

}

voidPrintfData()

{

cout << _year <<"/"<< _month <<"/"<< _day << endl;

}

private:

int_year;

int_month;

int_day;

};

intmain()

{

Data d1,d2;

d1.InitData(2022,5,21);

d1.PrintfData();

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

#include<iostream>

usingnamespacestd;

classData

{

public:

Data()

{

cout <<"Date()"<<this<< endl;

}

Data()

{

_year = year;

_month = month;

_day = day;

}

voidInitData(intyear = 1,intmonth = 1,intday = 1)

{

_year = year;

_month = month;

_day = day;

}

voidPrintfData()

{

cout << _year <<"/"<< _month <<"/"<< _day << endl;

}

private:

int_year;

int_month;

int_day;

};

intmain()

{

Data d1

return0;

}

上面的代码中,有两个默认的构造函数,因为不带参数的构造函数和全缺省的构造函数都被看为默认的构造函数,所以说,现在有两个构造函数,编译器不知道到底要去调用哪个构造函数,所以说,就会报错,所以我们删除一个就可以了。

关于编译器生成的默认成员函数,很多人会有疑惑:在我们不实现构造函数的情况下,编译器会生成默认的构造函数。但是看起来默认构造函数又没什么用?对象调用了编译器生成的默认构造函数,但是对象year/month/_day,依旧是随机值。也就说在这里编译器生成的默认构造函数并没有什么用?

解答:C++把类型分成内置类型(基本类型)和自定义类型。内置类型就是语法已经定义好的类型:如int/char...,自定义类型就是我们使用class/struct/union自己定义的类型,看看下面的程序,就发发现编译器生成默认的构造函数会对自定类型成员_t调用的它的默认成员函数

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

classTime

{

public:

Time()

{

cout <<"Time()"<< endl;

_hour = 0;

_minute = 0;

_second = 0;

}

private:

int_hour;

int_minute;

int_second;

};

classDate

{

private:

// 基本类型(内置类型)

int_year;

int_month;

int_day;

// 自定义类型

Time _t;

};

intmain()

{

Date d;

return0;

}

什么意思呢,就是编译器会不管int,char这种基本类型,而会去管自定义类型

这是输出的结果

到此这篇关于C++浅析构造函数的特性的文章就介绍到这了


需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询