C++ 类成员的默认值是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2614809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the default value for C++ class members
提问by leeeroy
What is the default values for members of a struct and members of a class in c++, and how do these rules differ (e.g. between classes/structs/primitives/etc) ? Are there circumstances where the rules about the default values differs ?
c++ 中结构成员和类成员的默认值是什么,这些规则有何不同(例如在类/结构/基元/等之间)?是否存在有关默认值的规则不同的情况?
采纳答案by AnT
There are no differences between structs and classes in this regard in C++. They all are called just class types.
在 C++ 中,结构和类在这方面没有区别。它们都被称为类类型。
Members of class types have no default values in general case. In order to for a class member to get a deterministic value it has to be initialized, which can be done by
类类型的成员在一般情况下没有默认值。为了让类成员获得确定性值,必须对其进行初始化,这可以通过
- Default constructor of the member itself
- Constructor initializer list of the enclosing class
- Explicitly specified initializer for object of the enclosing class (that includes value-initialization and initialization with aggregate initializer).
- 成员本身的默认构造函数
- 封闭类的构造函数初始值设定项列表
- 为封闭类的对象显式指定初始化器(包括值初始化和使用聚合初始化器的初始化)。
Additionally, all objects with static storage duration are zero-initialized at the program startup.
此外,所有具有静态存储持续时间的对象在程序启动时都被零初始化。
Aside from the above cases, class members, once again, have no default values and will initially contain unpredictable garbage values.
除了上述情况,类成员再次没有默认值,并且最初将包含不可预测的垃圾值。
回答by Hans Passant
Yeah, there is one. If you initialize an object with the default constructor and use parentheses then the POD members will be zero initialized:
是的,有一个。如果使用默认构造函数初始化对象并使用括号,则 POD 成员将被初始化为零:
someClass * p = new someClass();