What is the default value for C++ class members(C++ 类成员的默认值是什么)
问题描述
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++ 类成员的默认值是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 类成员的默认值是什么
基础教程推荐
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
