11不支持指定的初始化列表作为C99

11不支持指定的初始化列表作为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.

什么是的标准委员会是否排除了对此类方便功能的支持?

What was the c++11 standard committee's rationale for excluding support for such a handy feature?

推荐答案

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 ++对将灵活性放在类型的 designer 一侧,这样设计人员可以使正确使用类型的操作变得容易,而错误使用则更加困难。让设计人员控制如何初始化类型是其中的一部分:设计人员确定构造函数,类内初始化程序等。

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

08-21 20:31