我知道在 class
中,成员按照列出的顺序进行初始化。这是否适用于将变量分组为 public
和 private
等?我的困惑是我无法弄清楚是否有偏好,例如 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 时,它明确指出成员是按照其在定义中出现的顺序构造的。这意味着无论 private
、public
或它们在类成员初始化列表中的列出方式如何,它们都将按照声明的顺序构造。
关于C++ 类成员初始化序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633206/