当我们像这样初始化数组时 int a[5] = {0},编译器将所有 5 个元素设为 0。这非常好,紧凑的初始化和有用的功能。
但我想知道为什么编译器没有类似地初始化 int a[5]={1}?为什么它不使所有 5 个元素都为 1?为什么标准不强制执行它?这不是一个很棒的功能吗?是不是不见了?
此外,如果初始化器中的元素数量小于数组的大小,则编译可以使用初始化器中的最后一个元素初始化剩余元素。也就是说,int a[5]={1,2,3} 等同于 int a[5]={1,2,3,3,3}。同样,int a[10]={1,2,3,0} 等价于 int a[10]={1,2,3,0,0,0, 0,0,0,0};.
Designated initializers can be
combined with regular initializers, as
in the following example:
int a[10] = {2, 4, [8]=9, 10}
In this
example, a[0] is initialized to 2,
a1 is initialized to 4, a[2] to a[7]
are initialized to 0, and a[9] is
initialized to 10.
很有趣。但即使是这个特性也不在 C++ 中。
最佳答案
Why does it not make all 5 elements 1?
因为您误解了 {} 的含义。 (实际上,在 C++ 中,执行此操作的更好方法是 {} 而不是 {0})。语法 {0} 并不意味着您希望聚合中的所有元素都设置为零。相反,它表示您希望将第一个元素为零的聚合分配给指示的变量(在 C++ 中可以是数组或类类型)。由于聚合通常具有比零值更多的字段,因此聚合中的其余元素是默认构造的。内置或 POD 类型的默认值是将所有字段设置为零,因此您实际上已将整个聚合设置为零。
至于具体为什么,请考虑以下内容。根据当前标准,以下断言都不会失败:
struct abc
{
char field1;
int field2;
char field3;
};
int main()
{
abc example = {'a', static_cast<int>('b')};
//All three asserts pass
assert(example.field1 == 'a');
assert(example.field2 == static_cast<int>('b'));
assert(example.field3 == '\0');
int example2[3] = {static_cast<int>('a'), 42};
assert(example2[0] == static_cast<int>('a'));
assert(example2[1] == 42);
assert(example2[2] == 0);
}