C ++类成员的默认值是什么 [英] What is the default value for C++ class members
问题描述
在c ++中,结构的成员和类的成员的默认值是什么,以及这些规则如何不同(例如,在classes / structs / primitives / etc之间)?有没有在默认值的规则不同的情况下?
在这方面结构和类之间没有区别C ++ 。它们都只是类类型。
类类型的成员在一般情况下没有默认值。为了使类成员获得确定的值,必须初始化,这可以通过
来完成。-
- 封装类的构造函数初始化器列表
- 为封装类的对象显式指定初始化器(包括值
此外,具有静态存储持续时间的所有对象在程序启动时都是零初始化。 / p>
除了上述情况,类成员再次没有默认值,并且最初包含不可预测的垃圾值。
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 ?
There are no differences between structs and classes in this regard in C++. They all are called just class types.
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 form the above cases, class members, once again, have no default values and will initially contain unpredictable garbage values.
这篇关于C ++类成员的默认值是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!