C++直接初始化字段与默认构造函数中的初始化列表

标签 c++

我想知道这段代码是否有区别:

class Foo{
 private:
    int a = 0;
 public:
    Foo(){}
}

还有:

class Foo{
 private:
    int a;
 public:
    Foo(): a(0) {}
}

如果是这样,应该首选哪个? 我知道使用初始化列表比在构造函数主体中分配更好,但是初始化列表与在字段声明中直接初始化(至少对于原始类型,就像这里的情况一样)呢?

还有,下面是什么情况:

class Foo{
 private:
   int a = 0;
 public:
   Foo(){}
   Foo(int i): a(i) {}
}

当非默认构造函数被调用时:“a”被初始化了两次,先为0然后为“i”,还是直接为“i”?

最佳答案

来自 cppreference - Non-static data members

Member initialization
1) In the member initializer list of the constructor.
2) Through a default member initializer, which is simply a brace or equals initializer included in the member declaration, which is used if the member is omitted in the member initializer list.

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.


总之,这两个初始化器是等价的,并且做它们应该做的事情。

如果我仍然使用默认构造函数,或者如果所有或大多数构造函数将成员初始化为相同的值,我更喜欢默认成员初始化器。

class Foo {
private:
    int a = 0;
};

但是,如果所有构造函数都将成员初始化为不同的值,则使用默认成员初始值设定项意义不大,然后在各自的构造函数中进行显式初始化会更清晰

class Foo {
private:
    int a;
public:
    Foo() : a(3) {}
    Foo(int i) : a(i) {}
};

关于C++直接初始化字段与默认构造函数中的初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40378205/

相关文章:

c++ - 结构中的字符数组 - 不更新?

c++ - 从二进制文件中检索内存块

c++ - 在 std::map 中存储结构实例

c++ - 假设没有公共(public)代码,将公共(public)代码移动到基类是好习惯吗?

java - Mac笔记本电脑使用和开发讨论?

c# - 同一 COM 库中的 C++ 和 C# 类

c++ - QMainWindow 不再是事件窗口

c++ - 将 constexpr const char* 传递给模板函数?

c++ - 使用 libconfig 导入数组或列表设置

c++ - Raspberry Pi,C++计时功能,对值的运算?