在结构中初始化默认值 [英] Initializing default values in a struct
问题描述
如果我需要初始化一个C ++结构的几个选择值,这将是正确的:
If I needed to initialize only a few select values of a C++ struct, would this be correct:
struct foo {
foo() : a(true), b(true) {}
bool a;
bool b;
bool c;
} bar;
我认为我最终会得到一个 struct
项目 bar
与元素 bar.a = true
, bar.b = true
和未定义的 bar.c
?
Am I correct to assume I would end up with one struct
item called bar
with elements bar.a = true
, bar.b = true
and an undefined bar.c
?
推荐答案
是的。 bar.a
和 bar.b
设置为true,但 bar.c
未定义。
Yes. bar.a
and bar.b
are set to true, but bar.c
is undefined. However, certain compiler will set it to false.
查看实例: struct demo
根据C ++标准第8.5.12节:
According to C++ standard Section 8.5.12:
if不执行初始化,具有自动或动态存储持续时间的
对象具有不确定的值
if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value
对于原始内置数据类型( bool ,char,wchar_t,short,int,long,float,double,long double),只有全局变量它们没有显式初始化。
For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.
如果你不想要未定义的 bar.c
也应该像对 bar.a
和 bar.b
一样进行初始化。
If you don't really want undefined bar.c
to start with, you should also initialize it like you did for bar.a
and bar.b
.
这篇关于在结构中初始化默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!