在C++中的数据成员之前调用构造函数

Is constructor called in before the data members in C++

你好,我是学习 C++ 的新手。 构造函数是按照我在 class 中创建它的顺序创建的,还是总是在 class.

中创建任何其他内容之前先调用它
#include <iostream>
using namespace std;

class NonStatic 
{
    public:
        int no = 2;

    NonStatic():no(0) {
        
    }
};

int main() {
    NonStatic obj1;
    cout << obj1.no;
    
    return 0;
}

在此class。构造函数是在数据成员之前创建还是在数据成员之后创建

询问构造函数何时创建确实没有意义,它是代码,因此是在编译时创建的。

如果您要问默认成员初始化 int no = 2; 或构造函数初始化 : no(2) 哪个优先,那就是后者。

可以 假设 class 将其设置为二,然后构造函数将其设置为零,但这实际上没有意义。如果构造函数总是这样做,则默认值无关紧要,因此可能什么都不做。

当然,如果调用了一个不同的构造函数,它没有初始化no,它会得到默认值。

对于int no = 2;no通过default member initializer初始化为2。对于 NonStatic():no(0) {}no 通过成员初始化列表初始化为 0。然后忽略默认成员初始化器,对于NonStatic obj1;obj1.no将被初始化为0作为结果。

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored for that constructor.

关于initialization order,首先初始化数据成员(通过默认成员初始化器或成员初始化器列表),然后执行构造函数体。

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

  1. ...

  2. ...

  3. Then, non-static data member are initialized in order of declaration in the class definition.

  4. Finally, the body of the constructor is executed