C++ 类成员初始化序列

标签 c++ class initialization private public

我知道在 class 中,成员按照列出的顺序进行初始化。这是否适用于将变量分组为 publicprivate 等?我的困惑是我无法弄清楚是否有偏好,例如 private 成员按照它们在 public 成员之前列出的顺序进行初始化,而不管私有(private)变量在哪里列出关于类声明中的公众(我知道对基类成员存在这种偏见)

最佳答案

类初始化的规则在[class.base.init]/11中有详细说明

In a non-delegating constructor, initialization proceeds in the following order:

  • First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.

  • Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

  • Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

8 Finally, the compound-statement of the constructor body is executed.

[ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. —end note ]

强调我的

因此,当我们查看项目符号 3 时,它明确指出成员是按照其在定义中出现的顺序构造的。这意味着无论 privatepublic 或它们在类成员初始化列表中的列出方式如何,它们都将按照声明的顺序构造。

关于C++ 类成员初始化序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633206/

相关文章:

java - 以最有效和可读的方式进行条件初始化

c++ - 具有不同模板类型的子类的多态性

c++ - ISO C++ 禁止声明没有类型的 “parameter”

c++ - 用来自另一个容器的迭代器填充一个容器

c++ - OpenCV SVM 参数的推荐值

python - 将指针传递给导入的扩展类型方法时出错,而无需导入的同一类没有问题

ios - 如何在 Swift 中为不同文件中的类定义函数?

c++ - std vector 中数据类型的初始化

swift - 为什么 Swift 不允许在 class init 中给 self 赋值,而在 protocol init 中却不允许?

c++ - 如何在 C++ 中同时写入和读取文件