是一个C的成员++默认结构初始化为0? [英] Are members of a C++ struct initialized to 0 by default?

查看:111
本文介绍了是一个C的成员++默认结构初始化为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的结构

   struct Snapshot
    {
        double x; 
        int   y ;

    };

我想 X 为0,他们是否默认为0或做我必须做的

I want x and y to be 0. Will they be 0 by default or do I have to do:

Snapshot s= {0,0};

什么其他的方法来零出结构呢?

What are the other ways to zero out the structure?

推荐答案

他们不为空,如果你不初始化结构。

They are not null if you don't initialize the struct.

Snapshot s; // receives no initialization
Snapshot s = {}; // value initializes all members

第二将使所有成员为零,先使他们在未指定的值。需要注意的是它是递归

The second will make all members zero, the first leaves them at unspecified values. Note that it is recursive:

struct Parent { Snapshot s; };
Parent p; // receives no initialization
Parent p = {}; // value initializes all members

第二个将附言:{X,Y} 为零。如果你已经在你的结构有构造函数,你不能使用这些聚合初始化列表。如果是这样的话,你将不得不适当initalization添加到这些构造

The second will make p.s.{x,y} zero. You cannot use these aggregate initializer lists if you've got constructors in your struct. If that is the case, you will have to add proper initalization to those constructors

struct Snapshot {
    int x;
    double y;
    Snapshot():x(0),y(0) { }
    // other ctors / functions...
};

将初始化x和y为0。请注意,您可以使用 X(),Y()来初始化它们自己的类型忽略:那是当时值初始化,通常产生一个适当的初始值(0为INT,0.0双,呼吁有用户用户自定义类型的默认构造函数中声明的构造,...)。这是很重要的,特别是如果你的结构是一个模板。

Will initialize both x and y to 0. Note that you can use x(), y() to initialize them disregarding of their type: That's then value initialization, and usually yields a proper initial value (0 for int, 0.0 for double, calling the default constructor for user defined types that have user declared constructors, ...). This is important especially if your struct is a template.

这篇关于是一个C的成员++默认结构初始化为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆