简体   繁体   English

在结构中初始化默认值

[英]Initializing default values in a struct

If I needed to initialize only a few select values of a C++ struct, would this be correct:如果我只需要初始化 C++ 结构的几个选择值,这是否正确:

struct foo {
    foo() : a(true), b(true) {}
    bool a;
    bool b;
    bool c;
 } bar;

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 struct项,其中包含元素bar.a = truebar.b = true和一个未定义的bar.c

You don't even need to define a constructor你甚至不需要定义一个构造函数

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign).澄清一下:这些被称为大括号或等号初始化器(因为您也可以使用大括号初始化而不是等号)。 This is not only for aggregates: you can use this in normal class definitions.这不仅适用于聚合:您可以在普通类定义中使用它。 This was added in C++11.这是在 C++11 中添加的。

Yes.是的。 bar.a and bar.b are set to true, but bar.c is undefined. bar.abar.b设置为 true,但bar.c未定义。 However, certain compilers will set it to false.但是,某些编译器会将其设置为 false。

See a live example here: struct demo在此处查看实时示例: struct demo

According to C++ standard Section 8.5.12:根据 C++ 标准第 8.5.12 节:

if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value如果不进行初始化,自动或动态存储时间的对象具有不确定的值

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.对于原始内置数据类型( bool 、 char 、 wchar_t 、 short 、 int 、 long 、 float 、 double 、 long double ),只有全局变量(所有静态存储变量)如果未显式初始化,则其默认值为零。

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 .如果你真的不想要 undefined bar.c开始,你也应该像对bar.abar.b一样初始化它。

You can do it by using a constructor, like this:您可以通过使用构造函数来做到这一点,如下所示:

struct Date
{
int day;
int month;
int year;

Date()
{
    day=0;
    month=0;
    year=0;
}
};

or like this:或者像这样:

struct Date
{
int day;
int month;
int year;

Date():day(0),
       month(0),
       year(0){}
};

In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).在你的情况下 bar.c 是未定义的,它的值取决于编译器(而 a 和 b 被设置为 true)。

An explicit default initialization can help:显式默认初始化可以帮助:

struct foo {
    bool a {};
    bool b {};
    bool c {};
 } bar;

Behavior bool a {} is same as bool b = bool();行为bool a {}等同于bool b = bool(); and return false .并返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM