問題描述
c++ 中結構成員和類成員的默認值是什么,這些規則有何不同(例如,在類/結構/原語/等之間)?是否存在有關默認值的規則不同的情況?
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++ 中,結構和類在這方面沒有區別.它們都被稱為類類型.
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
- 成員自身的默認構造函數
- 封閉類的構造函數初始化列表
- 為封閉類的對象顯式指定初始化器(包括值初始化和使用聚合初始化器的初始化).
此外,所有具有靜態存儲持續時間的對象在程序啟動時都被零初始化.
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.
這篇關于C++ 類成員的默認值是什么的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!