简体   繁体   English

C++:存在构造函数的结构初始化

[英]C++: struct initialization in presence of constructor

I have question on C++ behavior when initializing structures using a list.我对使用列表初始化结构时的 C++ 行为有疑问。 For example, the following code behaves the same in C and C++.例如,以下代码在 C 和 C++ 中的行为相同。 The list initializes x :该列表初始化x

struct X {
    int x;
};

int main(int argc, char *argv[])
{
    struct X xx = {0};    
    return 0;
}

Now, if I add a constructor, I find out through testing that the constructor is called instead of the simple initialization of the x member:现在,如果我添加一个构造函数,我通过测试发现调用的是构造函数,而不是x成员的简单初始化:

#include <iostream>
using namespace std;

struct X {
    int x;
    X(int);
};

X::X(int i)
{
    cout << "X(int i)" << endl;
    x = i;
}

int main(int argc, char *argv[])
{
    struct X xx = {0};

    return 0;
}

Output: Output:

X(int i)

Is the behavior of C++ with an identical constructor (as above) to override the simple list initialization? C++ 的行为是否具有相同的构造函数(如上)来覆盖简单列表初始化? Giving my testing that is what appears to happen.进行我的测试似乎就是这样。

Thanks!谢谢!

The following syntax:以下语法:

X xx = {0};

is just a form of copy-list initialization .只是 复制列表初始化的一种形式。 This has the effect of invoking the constructor of X , as you observed.正如您所观察到的,这具有调用X的构造函数的效果。

The name of this initialization comes from the fact that this looks like a list is being copied, but just the regular constructor is invoked.这个初始化的名字来源于这样一个事实,它看起来像一个正在复制的列表,但只是调用了常规构造函数。 Note that this will only consider implicit constructors.请注意,这只会考虑implicit构造函数。

Also the elaborated-type-specifier struct is not necessary in c++, in the declaration of xx .xx的声明中,c++ 中也不需要详细说明类型说明符struct

Note that if you don't provide a constructor such as X(int) (as you did in the first example), then the declaration of xx will instead do aggregate initialization.请注意,如果您不提供诸如X(int)之类的构造函数(就像您在第一个示例中所做的那样),那么xx的声明将改为进行聚合初始化。

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

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