Why does C++11 not support designated initializer lists as C99?(为什么 C++11 不支持 C99 指定的初始化列表?)
问题描述
考虑:
struct Person
{
int height;
int weight;
int age;
};
int main()
{
Person p { .age = 18 };
}
上面的代码在 C99 中是合法的,但在 C++11 中是不合法的.
The code above is legal in C99, but not legal in C++11.
什么是 c++11 标准委员会不支持这样一个方便的功能的理由是什么?
What was the c++11 standard committee's rationale for excluding support for such a handy feature?
推荐答案
C++ 有构造函数.如果只初始化一个成员是有意义的,那么可以通过实现适当的构造函数在程序中表达.这是 C++ 提倡的那种抽象.
C++ has constructors. If it makes sense to initialize just one member then that can be expressed in the program by implementing an appropriate constructor. This is the sort of abstraction C++ promotes.
另一方面,指定初始值设定项功能更多的是公开和使成员易于直接在客户端代码中访问.这会导致诸如拥有一个 18 岁(岁?)但身高和体重为零的人.
On the other hand the designated initializers feature is more about exposing and making members easy to access directly in client code. This leads to things like having a person of age 18 (years?) but with height and weight of zero.
换句话说,指定的初始化器支持公开内部结构的编程风格,并且客户端可以灵活地决定他们希望如何使用该类型.
In other words, designated initializers support a programming style where internals are exposed, and the client is given flexibility to decide how they want to use the type.
C++ 更感兴趣的是将灵活性放在类型的设计者 方面,因此设计者可以轻松正确地使用类型而难以使用不当.让设计者控制如何初始化类型是其中的一部分:设计者确定构造函数、类内初始化器等.
C++ is more interested in putting the flexibility on the side of the designer of a type instead, so designers can make it easy to use a type correctly and difficult to use incorrectly. Putting the designer in control of how a type can be initialized is part of this: the designer determines constructors, in-class initializers, etc.
这篇关于为什么 C++11 不支持 C99 指定的初始化列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 C++11 不支持 C99 指定的初始化列表?


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01