gpt4 book ai didi

c++ - struct Data d = {0} 和 struct Data d = {} 有区别吗

转载 作者:可可西里 更新时间:2023-11-01 18:36:41 26 4
gpt4 key购买 nike

我的代码中有两种类型的结构变量初始化。

例子

#include<iostream>
#include<string>
using namespace std;
struct Data{
int arr[5];
float x;

};
int main(){
struct Data d = {0};
struct Data d1 = {};
cout<<d.arr[0]<<d.x;
cout<<d1.arr[0]<<d1.x<<endl;
return 0;
}

我正在运行代码广告,输出为 0 0 0 0。请帮助我,这两种初始化之间有什么区别吗。

最佳答案

根据aggregate initialization的规则,这里的效果是一样的,即结构的所有成员都是 value-initialized (zero-initialized 此处用于非类类型)。

If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed.

更准确地说,

struct Data d = {0}; // initialize the 1st member of Data to 0, value-initialize(zero-initialize) the remaining members
struct Data d1 = {}; // value-initialize(zero-initialize) all the members of Data

请注意,整个故事是基于 Data 是一个 aggregate type并且它的成员是非类类型,否则行为会根据list initialization的规则改变.

关于c++ - struct Data d = {0} 和 struct Data d = {} 有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40757144/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com