这两种方法在C++中实现函数的区别是什么?

Kin*_*ani 1 c++ function

假设我有一个复制构造函数

第一种方式:

Car(Car const& other)
     : Model{other.Model}, Something{other.Something}
{}
Run Code Online (Sandbox Code Playgroud)

第二种方式:

Car(Car const& other) 
{
Model = other.Model; 
Something = other.Something; 
}
Run Code Online (Sandbox Code Playgroud)

Alp*_*per 5

第一个版本(Constructor Initializer List)是initializes其数据成员,而第二个版本assigns是数据成员的值.

如果数据成员未显式initialized位于构造函数初始值设定项列表中,则initialized在构造函数体开始执行之前,该成员是缺省值.它的重要程度取决于数据成员类型,因此,优先考虑第一个版本(Constructor Initializer List).

必须是constreference类型的数据成员initialized.此外,class必须也没有默认构造函数的类型数据成员initialized.