我有这样的结构:

struct Snapshot
{
    double x; 
    int y;
};

我想让x和y等于0。它们是默认为0还是我必须这样做:

Snapshot s = {0,0};

还有什么方法可以把结构归零呢?


当前回答

将pod成员移动到基类以缩短初始化列表:

struct foo_pod
{
    int x;
    int y;
    int z;
};

struct foo : foo_pod
{
    std::string name;
    foo(std::string name)
        : foo_pod()
        , name(name)
    {
    }
};

int main()
{
    foo f("bar");
    printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}

其他回答

在c++中,使用无参数构造函数。在C语言中,你不能有构造函数,所以使用memset或者——有趣的解决方案——指定初始化器:

struct Snapshot s = { .x = 0.0, .y = 0.0 };

将pod成员移动到基类以缩短初始化列表:

struct foo_pod
{
    int x;
    int y;
    int z;
};

struct foo : foo_pod
{
    std::string name;
    foo(std::string name)
        : foo_pod()
        , name(name)
    {
    }
};

int main()
{
    foo f("bar");
    printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}

我知道这个问题已经非常老了,但是这个问题突然出现在谷歌上,我找到了另一种方式,我想我应该把它加在这里:

Snapshot s {};

我不确定这个语法需要哪个C/ c++语言版本。

不,默认不为0。确保所有值或默认值为0的最简单方法是定义一个构造函数

Snapshot() : x(0), y(0) {
}

这确保了Snapshot的所有使用都有初始化的值。

一般来说,没有。然而,在函数/中声明为文件作用域或静态作用域的结构体将被初始化为0(就像那些作用域的所有其他变量一样):

int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0

void foo() {
  struct { int a, b; } bar; // undefined
  static struct { int c, d; } quux; // 0, 0
}