成员初始值设定项列表是否被视为构造函数 body 的一部分,或者它是否被视为声明符的一部分

Is member initializer list considered part of the body of a constructor or it it considered part of the declarator

我正在学习 C++ 中的成员初始值设定项列表。因此请考虑以下示例:

struct Person
{
    public:
        Person(int pAge): age(pAge)
//                        ^^^^^^^^^ is this member initializer formally part of the constructor body? 
        {
        }
    private:
        int age = 0;
};

我的第一个问题是,它是成员初始值设定项age(pAge) 正式 构造函数body 的一部分。我的意思是我读过一个函数的 body 从开头 { 开始并在结尾 } 结束。据我目前的理解,这里涉及四件事:

  1. Ctor定义:这包括整个
//this whole thing is ctor definition
Person(int pAge): age(pAge)
        {
        }
  1. 成员初始值设定项:这是age(pAge)部分。

  2. Ctor声明:这是Person(int pAge)部分。

  3. Ctor 的body:这是开盘{和收盘}之间的区域。

我的第二个问题是上面给出的描述是否正确?如果不是,那么根据 C++ 标准,这四个术语的正确含义应该是什么:Ctor 定义成员初始值设定项 Ctor声明Ctor的body.

PS:我读过 post 没有回答我的问题。

在您的示例中,age(pAge) 是实现的一部分,而不是声明。如果您将其更改为 age(pAge+1),调用者不会改变。构造函数的实现会调用基类构造函数,然后是默认构造函数或者像age(pAge)这样的构造函数,顺序记不住了,然后是编译后的构造函数源码。我会认为语法有点奇怪。

is the member initializer age(pAge) formally part of the constructor's body?

是,从Constructors and member initializer lists开始:

The body of a function definition of any constructor, before the opening brace of the compound statement, may include the member initializer list, whose syntax is the colon character :, followed by the comma-separated list of one or more member-initializers,...


is the above given description correct?

在第二个问题的第 4 点中,构造函数的主体还包括上面引用的成员初始化列表。

根据[dcl.fct.def.general],它告诉我们函数定义的语法,ctor-initializerfunction-body:

的一部分
function-definition:
    [...] function-body

function-body:
    ctor-initializer_opt compound-statement

compound-statement,根据 [stmt.block],在这种情况下,OP 指的是“大括号内”():

A compound statement (also known as a block) groups a sequence of statements into a single statement.

compound-statement:
    { statement-seq_opt }

鉴于 ctor-initializer,根据 [class.base.init],特别允许仅用于作为构造函数的特殊类型的函数 [emphasis 我的]:

In the definition of a constructor for a class, initializers for direct and virtual base class subobjects and non-static data members can be specified by a ctor-initializer, which has the form

ctor-initializer:
: mem-initializer-list

有了这个,我们就可以回答OP的问题了。


Is member initializer list considered part of the body of a constructor or it it considered part of the declarator

是的,根据上面的成员初始值设定项,形式上 mem-initializer-listfunction-body[=68= 的一部分] 的构造函数。


My second question is that is the above given description correct?

1. Ctor definition: This includes the whole

//this whole thing is ctor definition
Person(int pAge): age(pAge)
        {
        }

正确。

2. Member initializer: This is the age(pAge) part.

正确,正式的 mem-initializer-list(而 : age(pAge)ctor-initializer

3. Ctor declaration: This is the Person(int pAge) part.

不完全正确:定义也是声明。 [dcl.fct]描述了函数声明的规则,简单来说,Person(int pAge);是一个不是定义的声明,特别是这里省略了一个function-body.

4. Ctor's body: This is the region between the opening { and the closing }.

不正确。函数体,如上所述,容器也可以是 ctor-initializer。在OP的示例中,: age(pAge) {}是构造函数的function-body