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 structs 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>初始化
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
