为什么 C++11 不支持 C99 指定的初始化列表? [英] Why does C++11 not support designated initializer lists as C99?

查看:27
本文介绍了为什么 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.

什么是 标准委员会不支持这样一个方便的功能的理由是什么?

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 指定的初始化列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆