std::arraylt;Tgt; initialization(std::arraylt;Tgt;初始化)
问题描述
std::array<T>
本质上是包装在 struct
中的 C 样式数组.struct
的初始化需要大括号,数组的初始化也需要大括号.所以我需要两对大括号:
A std::array<T>
is essentially a C-style array wrapped in a struct
. The initialization of struct
s requires braces, and the initialization of arrays requires braces as well. So I need two pairs of braces:
std::array<int, 5> a = {{1, 2, 3, 4, 5}};
但是我看到的大多数示例代码只使用了一对大括号:
But most of the example code I have seen only uses one pair of braces:
std::array<int, 5> b = {1, 2, 3, 4, 5};
为什么允许这样做,与第一种方法相比,它有什么好处或缺点?
How come this is allowed, and does it have any benefits or drawbacks compared to the first approch?
推荐答案
这样做的好处是你有...更少的输入.但缺点是只有在声明具有该形式时才允许您省略大括号.如果您不使用 =
,或者如果数组是一个成员并且您使用 member{{1, 2, 3, 4, 5}}
对其进行初始化,则您不能只传递一对大括号.
The benefit is that you have ... less to type. But the drawback is that you are only allowed to leave off braces when the declaration has that form. If you leave off the =
, or if the array is a member and you initialize it with member{{1, 2, 3, 4, 5}}
, you cannot only pass one pair of braces.
这是因为在将大括号传递给函数时,担心可能出现重载歧义,如 f({{1, 2, 3, 4, 5}})
.但这引起了一些讨论,并生成了问题报告.
This is because there were worries of possible overload ambiguities when braces are passed to functions, as in f({{1, 2, 3, 4, 5}})
. But it caused some discussion and an issue report has been generated.
基本上,= { ... }
初始化总是能够省略大括号,如
Essentially, the = { ... }
initialization always has been able to omit braces, as in
int a[][2] = { 1, 2, 3, 4 };
这并不新鲜.新的是你可以省略 =
,但是你必须指定所有的大括号
That's not new. What is new is that you can omit the =
, but then you must specify all braces
int a[][2]{ {1, 2}, {3, 4} };
这篇关于std::array<T>初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::array<T>初始化


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