有没有办法通过一个匿名数组在C ++中的说法? [英] Is there any way to pass an anonymous array as an argument in C++?

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

问题描述

我希望能够,申报一个数组在C函数参数++中所示的例子code以下(不编译)。有没有办法做到这一点(除另行声明数组事前)?

 的#include<&stdio.h中GT;静态无效PrintArray(INT arrayLen,const int的*数组)
{
   的for(int i = 0; I< arrayLen;我++)的printf(%I - >%I \\ N,我,阵列[我]);
}INT主(INT,CHAR **)
{
   PrintArray(5,{5,6,7,8,9}); //不能编译
   返回0;
}


解决方案

没有。这不是由标准允​​许的。 匿名阵你指的实际上是一个的初始化列表的。初始化列表将被正式承认为C ++ 0x中的对象。现在,他们只是初始化C-阵列和POD类型语法。

例如,下面也不起作用:

  INT的main()
{
    INT * P;
    P = {1,2,3}; //无效C或C ++
}

编辑:现在,C ++ 11已经出来了,这可以与内置的 initializer_list 键入完成。耶!

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;
}

解决方案

No. This is not allowed by the standard. The "anonymous array" you refer to is actually an initializer list. Initializer lists will be formally recognized as objects in C++0x. For now, they are just a syntax for initializing c-arrays and POD types.

For example, the following also does not work:

int main()
{
    int* p;
    p = {1, 2, 3}; // not valid C or C++
}

EDIT: Now that C++11 is out, this can be done with the built-in initializer_list type. Yay!

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

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