相关概念及注意事项:
- 类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。
- 构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不能指定返回类型,也不会返回
void
。构造函数可用于为某些成员变量设置初始值。 - 默认的构造函数没有任何参数,但如果需要,构造函数也可以带有参数。
- 可以使用初始化列表来初始化字段;
- 一般地,除非有明显的理由想要定义隐式转换,否则单形参构造函数应该为
explicit
。将构造函数设置为explicit
可以避免错误,如果真需要转换,可以显式构造对象。 - 构造函数的作用是初始化数据成员。如果类的数据成员是
const
对象,类类型对象,那这些对象的初始化只能在初始化列表中进行。 - 构造函数决定了对象定义时的形式。
- 类有重载的构造函数,或者类带默认参数的构造函数时候,需要注意不能有冲突的构造函数形式。
- 只要自己定义了任何形式的构造函数,则编译器不会合成默认构造函数。如果需要默认构造函数,那需要显式定义无参数的构造函数。
代码涉及内容:
作用:保证每个对象的数据成员具有合适的初始值;
构造函数初始化式
默认实参与构造函数
默认构造函数
隐式类类型转换
类成员的显式初始化
1 | #include <iostream> |
执行结果: