C++ 类:在不重载构造函数的情况下初始化属性

C++ Classes: Initializing attributes without constructor overloading

来自 JavaScript 和 Python,我试图了解 C++ class 构造函数的细微差别和目的。

在下面的示例中,为什么可以在没有构造函数的情况下初始化属性?

class MyClass {
public:
    int a = 1;
    int b = 2;
};

默认构造函数是否包括上面的definitions/initializations?下面两个例子有什么区别?:

1.

class MyClass {
public:
    int a;
    int b;
    MyClass(){
        a = 1;
        b = 2;
    }
};
  1. JavaScript/Python风格(这可能吗?)
class MyClass {
public:
    MyClass(){
        // Some kind of variable declaration and definition like:
        // this.a = 1;
        // this.b = 2;
    }
};

对我来说,在没有构造函数的情况下进行初始化的选项听起来有点矫枉过正,而且令人困惑。在 Python 和 JavaScript 中,通常从构造函数中声明和初始化所有变量,而且只能从那里声明和初始化。

这里的最佳做法是什么?

In the example below, why is it allowed to initialize attributes without a constructor?

因为 C++11 专门添加了那个特性。参见 Member initialization

Does the default constructor include the above definitions/initializations?

是的。此代码:

class MyClass {
public:
    int a = 1;
    int b = 2;
};

是否大致(不完全)等同于此代码:

class MyClass {
public:
    int a;
    int b;

    MyClass() : a(1), b(2) {}
};

实际上可以同时使用两种形式的初始化,eg:

class MyClass {
public:
    int a = 1;
    int b = 2;

    MyClass() = default;
    MyClass(int a) : a(a) {}
};

根据 Member initialization:

Non-static data members may be initialized in one of two ways:

  1. In the member initializer list of the constructor.

  2. Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

    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.

a成员未在default constructor's member initialization list中指定,因此在默认构造MyClass对象时将使用默认值1初始化。

a 成员在 converting constructor's member initialization list 中显式初始化,因此其默认值 1 将被忽略,而是使用 caller-provided 值初始化当使用输入值构造 MyClass 对象时。

b 成员未在任一构造函数的 member initialization list 中指定,因此它将始终使用其默认值 2 进行初始化。

What is the difference to the following two examples?:

第一个示例是您在 C++11 之前必须做的事情(如果您没有使用构造函数的 member initialization list,如上所示)。

第二个例子在 C++ 中是不合法的。您不能动态地 声明 成员,当然也不能从构造函数内部声明。它们必须在 class 声明本身中静态声明。