如果我只需要初始化C++结构的几个选择值,那么这是正确的:
struct foo {
foo() : a(true), b(true) {}
bool a;
bool b;
bool c;
} bar;
Run Code Online (Sandbox Code Playgroud)
我是正确的假设我最终会与一个struct
叫项bar
的元素bar.a = true
,bar.b = true
和一个未定义的bar.c
?
Eri*_*zen 192
您甚至不需要定义构造函数
struct foo {
bool a = true;
bool b = true;
bool c;
} bar;
Run Code Online (Sandbox Code Playgroud)
澄清一下:这些被称为大括号或大小相等(因为你也可以使用大括号初始化而不是等号).这不仅适用于聚合:您可以在普通的类定义中使用它.这是在C++ 11中添加的.
tao*_*ocp 33
是.bar.a
并bar.b
设置为true,但bar.c
未定义.但是,某些编译器会将其设置为false.
在这里查看一个实例:struct demo
根据C++标准第8.5.12节:
如果未执行初始化,则具有自动或动态存储持续时间的对象具有不确定的值
对于原始内置数据类型(bool,char,wchar_t,short,int,long,float,double,long double),如果未显式初始化,则只有全局变量(所有静态存储变量)的默认值为零.
如果你真的不想不确定bar.c
,开始时,你也应该像你这样的初始化bar.a
和bar.b
.
您可以使用构造函数来执行此操作,如下所示:
struct Date
{
int day;
int month;
int year;
Date()
{
day=0;
month=0;
year=0;
}
};
Run Code Online (Sandbox Code Playgroud)
或者像这样:
struct Date
{
int day;
int month;
int year;
Date():day(0),
month(0),
year(0){}
};
Run Code Online (Sandbox Code Playgroud)
在你的情况下,bar.c是未定义的,它的值取决于编译器(而a和b设置为true).
显式默认初始化可以帮助:
struct foo {
bool a {};
bool b {};
bool c {};
} bar;
Run Code Online (Sandbox Code Playgroud)
行为与和 returnbool a {}
相同。bool b = bool();
false
归档时间: |
|
查看次数: |
126795 次 |
最近记录: |