聚合初始化是针对数组或者类类型(通常为结构或者联合)的一种列表初始化形式。类类型(常为 struct 或 union)必须符合下面条件
- 没有私有或者受保护非静态数据成员
- 没有用户声明的构造函数
- 没有用户提供的构造函数(允许显式预置或弃置的构造函数)
- 没有用户提供、继承或 explicit 构造函数(允许显式预置或弃置的构造函数)
- 没有用户声明或者继承的构造函数
- 没有
虚、私有或受保护
(C++17 起)基类 - 没有虚拟成员函数
- 无默认成员初始化器(C++11 起)(C++14 前)
聚合初始化设定项包括含等号或者不含等号的括号内的初始化列表,如下示例所示:
#include <iostream>
using namespace std;
struct MyAggregate{
int myInt;
char myChar;
};
struct MyAggregate2{
int myInt;
char myChar = 'Z'; // member-initializer OK in C++14
};
int main() {
MyAggregate agg1{
1, 'c' };
MyAggregate2 agg2{
2};
cout << "agg1: " << agg1.myChar << ": " << agg1.myInt << endl;
cout << "agg2: " << agg2.myChar << ": " << agg2.myInt << endl;
int myArr1[]{
1, 2, 3, 4 };
int myArr2[3] = {
5, 6, 7 };
int myArr3[5] = {
8, 9, 10 };
cout << "myArr1: ";
for (int i : myArr1){
cout << i << " ";
}
cout << endl;
cout << "myArr3: ";
for (auto const &i : myArr3) {
cout << i << " ";
}
cout << endl;
}
在聚合初始化期间声明但未显式初始化的数组成员将进行零初始化,如上面所示 myArr3 。
初始化包含聚合的聚合
聚合类型可包含其他聚合类型,例如数组的数组、结构的数组等。 这些类型使用嵌套的大括号组进行初始化,例如:
struct MyStruct {
int myInt;
char myChar;
};
int main() {
int intArr1[2][2]{
{
1, 2 }, {
3, 4 }};
int intArr3[2][2] = {
1, 2, 3, 4};
MyStruct structArr[]{
{
1, 'a' }, {
2, 'b' }, {
3, 'c'} };
}