我发现了一个源文件 here (在 C 中)。它使用合理但奇怪的样式来初始化数组。我在一个较短的 C++ 程序中试了一下(请注意代码注释中的“旧方法”):
arr.cc
#include <iostream>
using namespace std;
int main() {
long arr[] = { [0] = 100, [1] = 101 }; // old way: long arr[] = { 100, 101 };
cout << arr[0] << " " << arr[1] << endl;
}
代码是这样编译的:
g++-6 -std=c++14 arr.cc -o arr
运行时,输出是这样的:
100 101
它通过 -std=c++14
了吗?但我无法在 C++ 引用网站(如 cppreference.com)中找到它。是否符合标准?如果是,从哪个版本开始?
最佳答案
这不是有效的 C++ 代码; C 标准采用了它,作为扩展,GCC 也允许在 C++ 中使用它。要使 GCC 符合 C++ 标准,您需要同时传递 -std=c++17
(或任何版本)和 -pedantic
。这样,your code does emit warnings saying it's nonstandard .这在 GCC 中如何工作的描述是 here .
请注意,您还可以使用 struct
成员来执行此操作,而不仅仅是数组;给予
struct Point
{
int x;
int y;
};
你可以说 Point p = {.x = 17}
。到目前为止,这在 C++ 中也是非标准的,但是 it will be adopted in C++2a .到目前为止,这仅适用于非数组版本;我不知道是否也有计划添加数组版本,或者它是否会在 C++2a 中实现。
关于c++ - 这段代码中的数组初始化风格是什么?是标准的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50146828/