数组类型的初始化(C++)
Initialization of array type (C++)
根据https://en.cppreference.com/w/cpp/language/list_initialization,列表初始化的作用之一是:
If T is an aggregate type, aggregate initialization is performed.
由于数组是聚合类型,当我初始化数组时int array[3] = {1, 2};
,
我相信发生的事情是
- 列表初始化
- 聚合初始化
- 复制初始化,其中 1、2 是从初始化列表的相应子句复制初始化的
- 剩余的值是值初始化的(零初始化)
这对我来说很有意义,因为数组的值将是
{1, 2, 0}.
然而,当我继续阅读时,我注意到列表初始化的另一个影响是:
If T is an aggregate type and the initializer list has a single
element of the same or derived type (possibly cv-qualified), the
object is initialized from that element (by copy-initialization for
copy-list-initialization, or by direct-initialization for
direct-list-initialization).
那么,在 "initializer list has a single element" 处声明一个数组 int array[3] = {1};
与当有多个元素时是不同的过程吗? (即 int array [3] = {1, 2};
)?这对我来说没有意义,但我不确定我错过了什么。
不会应用该效果,如引号所述,
If T is an aggregate type and the initializer list has a single element of the same or derived type (possibly cv-qualified), the object is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization).
给定 int array[3] = {1};
,{1}
具有 int
类型的单个元素 1
,它不是数组类型 [=14= 的相同类型或派生类型].
根据https://en.cppreference.com/w/cpp/language/list_initialization,列表初始化的作用之一是:
If T is an aggregate type, aggregate initialization is performed.
由于数组是聚合类型,当我初始化数组时int array[3] = {1, 2};
,
我相信发生的事情是
- 列表初始化
- 聚合初始化
- 复制初始化,其中 1、2 是从初始化列表的相应子句复制初始化的
- 剩余的值是值初始化的(零初始化)
这对我来说很有意义,因为数组的值将是 {1, 2, 0}.
然而,当我继续阅读时,我注意到列表初始化的另一个影响是:
If T is an aggregate type and the initializer list has a single element of the same or derived type (possibly cv-qualified), the object is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization).
那么,在 "initializer list has a single element" 处声明一个数组 int array[3] = {1};
与当有多个元素时是不同的过程吗? (即 int array [3] = {1, 2};
)?这对我来说没有意义,但我不确定我错过了什么。
不会应用该效果,如引号所述,
If T is an aggregate type and the initializer list has a single element of the same or derived type (possibly cv-qualified), the object is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization).
给定 int array[3] = {1};
,{1}
具有 int
类型的单个元素 1
,它不是数组类型 [=14= 的相同类型或派生类型].