有没有办法在 C++ 中将匿名数组作为参数传递? [英] Is there any way to pass an anonymous array as an argument in C++?

查看:35
本文介绍了有没有办法在 C++ 中将匿名数组作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在 C++ 中将数组声明为函数参数,如下面的示例代码所示(无法编译).有没有办法做到这一点(除了事先单独声明数组)?

I'd like to be able to declare an array as a function argument in C++, as shown in the example code below (which doesn't compile). Is there any way to do this (other than declaring the array separately beforehand)?

#include <stdio.h>

static void PrintArray(int arrayLen, const int * array)
{
   for (int i=0; i<arrayLen; i++) printf("%i -> %i\n", i, array[i]);
}

int main(int, char **)
{
   PrintArray(5, {5,6,7,8,9} );  // doesn't compile
   return 0;
}

推荐答案

如果您使用的是较旧的 C++ 变体(C++0x 之前的版本),则不允许这样做.您所指的匿名数组"实际上是一个初始化列表.现在 C++11 已经出来了,这可以通过内置的 initializer_list 类型来完成.理论上,您也可以通过使用 extern C 将其用作 C 风格的初始化列表,如果您的编译器将它们解析为 C99 或更高版本.

If you're using older C++ variants (pre-C++0x), then this is not allowed. The "anonymous array" you refer to is actually an initializer list. Now that C++11 is out, this can be done with the built-in initializer_list type. You theoretically can also use it as a C-style initializer list by using extern C, if your compiler parses them as C99 or later.

例如:

int main()
{
    const int* p;
    p = (const int[]){1, 2, 3};
}

这篇关于有没有办法在 C++ 中将匿名数组作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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