gpt4 book ai didi

c++ - 是否可以在 C++ 中使用初始化列表设置数组的特定成员?

转载 作者:搜寻专家 更新时间:2023-10-31 01:28:52 25 4
gpt4 key购买 nike

我知道你可以用这样的初始化列表来初始化整个数组:

struct s {
int a[1];
s (int b): a{b}{}
};

,但是是否可以设置一个特定成员的值?因为:

struct s {
int a[1];
s (int b): a[0]{}
};

不起作用并抛出两个错误:

expected '(' before '[' token  

expected '{' before '[' token.

最佳答案

您可以通过aggregate initialization 将值放在适当的位置来初始化数组的元素。 .

struct s {
int a[2];
s (int b): a{b, 0} {} // sets a[0] with the value of b
// a[1] is set to zero
};

s foo(1);
std::cout << foo.a[0] << " " << foo.a[1]; // 1 0

更新(感谢@NathanOliver)

缺少的元素是 zero initialized .

struct s {
int a[2];
s (int b): a{b} {} // a[1] is already 0
};

关于c++ - 是否可以在 C++ 中使用初始化列表设置数组的特定成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51025653/

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