文章目录
- [第一章 C++20核心语法特性](#第一章 C++20核心语法特性)
-
- [1.6 指定初始化 (Designated Initializers)](#1.6 指定初始化 (Designated Initializers))
-
- [1.6.1 语法规则](#1.6.1 语法规则)
- [1.6.2 示例](#1.6.2 示例)
本文记录C++20新特性之指定初始化 (Designated Initializers)。
第一章 C++20核心语法特性
1.6 指定初始化 (Designated Initializers)
C++20之前,初始化一个包含多个成员的结构体通常使用{}方式,按值的定义顺序进行初始化。
cpp
struct Window {
int x, y;
int width, height;
bool isVisible;
const char* title;
};
void test()
{
// C++20 之前:必须严格按照定义顺序,且容易混淆
Window w = { 10, 10, 800, 600, true, "Main" };
}
这种方式缺点是可读性差,看到10,800,需要对照定义顺序来查看表示的意思。
如果在结构体中添加或删除一个成员,所有初始化代码都要重新修改。
C++20引入了指定初始化,解决了上面的问题。
1.6.1 语法规则
cpp
.成员名 = 值。
比如:
cpp
Window w = { .x = 10, .y = 10, .title = "Main" };
需要注意:
- 按顺序指定,指定成员顺序必须与结构体成员定义顺序一致。
- 未指定的成员将使用默认的初始化值。
- 不能混用,不能又指定初始化,又普通初始化,例如 { .x = 1, 20 } 是非法的。
1.6.2 示例
示例1:C++20初始化
cpp
struct Date {
int year;
int month;
int day;
};
void printDate(const Date& d)
{
std::cout << d.year << "-" << d.month << "-" << d.day << std::endl;
}
void test()
{
// 之前写法
Date d1 = { 2025, 6, 15 };
printDate(d1);
// 2025-6-15
// C++20 写法
Date d2 = {
.year = 2025,
.month = 6,
.day = 2
};
printDate(d2);
// 2025-6-2
}
示例2:初始化指定的成员
cpp
struct ServerConfig {
int port = 8080; // 默认值
int max_connections = 100; // 默认值
bool enable_ssl = false; // 默认值
const char* name = "Default";
};
int test()
{
// 场景 1: 只修改端口,其他用默认值
ServerConfig c1 = { .port = 9090 };
// c1.max_connections 是 100, c1.enable_ssl 是 false
// 场景 2: 只开启 SSL,其他用默认值
// 注意:必须跳过前面的成员,不能乱序
ServerConfig c2 = { .enable_ssl = true };
// 场景 3: 错误示范 (乱序)
// ServerConfig c3 = { .enable_ssl = true, .port = 80 }; // 编译错误!port 定义在 enable_ssl 之前
return 0;
}
示例3:联合体 (Union) 的初始化
cpp
union Value {
int i;
float f;
char c;
};
int test() {
// C++20 之前:只能 Value v = { 10 }; (初始化 i)
// C++20:可以直接初始化 f
Value v = { .f = 3.14f };
return 0;
}